This is a basic PSR-6 implementation of cache using the filesystem
Install using composer
composer require overdesign/psr-cache
Basic example
<?php
use Overdesign\PsrCache\FileCacheDriver;
$cacheDir = __DIR__ . '/cache';
$cache = new FileCacheDriver($cacheDir);
$item = $cache->getItem('myItem');
if ($item->isHit()) {
echo 'Item found in cache';
var_dump($item->get());
} else {
$item->set('my data');
$item->expiresAfter(120); // Expire in 2 min
$cache->save($item);
}
The drivers only deletes expired files when you try to recover them explicitly.
In order to clean the cache files you have three methods.
clear()
Deletes all the items in the current pool
clearExpired()
Deletes all the expired items in the pool
gc()
Acts as a garbage collector
It's not recommended to call the gc()
method within the normal user flow operation as it can be a high time consuming operation.
The ideal option is to set a cron to call the gc()
method.
You can pass various options to the method, see the phpdoc to know more about that options.
- Add PSR-16 support