Limited FileCache for tmpfs memory caching

Something I came up with for my small-scale yii2 installation and figured might be useful for others as well: an extension of the standard FileCache which limits the total cache-size. This way it can be used for a shared memory cache (by setting /dev/shm or another tmpfs mount as cachePath), without having to worry about running out of memory due to excessive caching.

Usage is quite simple, just call it in your configuration:




        'cache' => [

            'class' => 'app\helpers\SizeLimitFileCache',

            'cachePath' => '/dev/shm/yiicache',

            'maxSize' => 10000000

        ],



Internally it inherits most of the standard FileCache, except instead of random garbage collection, upon storing a new value it checks total cache size. If cache size approaches the set limit, expired items get automatically purged. If after that it’s still running out of space, the oldest cache items get purged until enough space has been made available.

Good one. How about releasing it as an extension?