A cache implementation based on 500x faster caching and brick/varexporter.
composer require jasny/varcache
The Cache
object implements PSR-16 simple cache.
use Jasny\VarCache\Cache;
$cache = new Cache('path/to/cache/dir');
$service = $cache->get('service');
if ($service === null) {
$service = new Service();
// ... Initialize service
$cache->set('service', $service);
}
Caveat: Method has()
disregards the ttl.
The resolve
method takes a closure (without arguments). It will cache the return value of the function as PHP script.
On subsequent requests the closure isn't called, but the cached value is returned.
use Jasny\VarCache\Cache;
$cache = new Cache('path/to/cache/dir');
$service = $cache->resolve(function() {
$service = new Service();
// ... Initialize service
return $service;
});
The cache
function uses reflection to create a hash of the closure. Limited information about the closure is returned
through reflection. This means that changes to the code don't automatically result in a different hash.
During development, you may not want to cache. NoCache
is a null object that will not store anything.
use Jasny\VarCache\NoCache;
$cache = new NoCache();
$service = $cache->resolve(function() {
$service = new Service();
// ... Initialize service
return $service;
});