Cacheable Array
, (*1)
Provides an array-like object whose items are persisted to a PSR-16 cache instance., (*2)
Upon creation the object is populated with existing items from the cache, should they exist., (*3)
Items are saved into the cache when the instance is destroyed., (*4)
Note: No attempt is made to synchronise multiple instances of CacheableArray that use the same cache instance and cache key., (*5)
Requirements
Installation
Installation will usually consist of adding the library to a project's composer.json
file:, (*6)
{
"require": {
"serato/cacheable-array": "^1.0"
}
}
Usage
Create a Serato\CacheableArray\CacheableArray
instance by providing a Psr\SimpleCache\CacheInterface
instance and a cache key:, (*7)
use Serato\CacheableArray\CacheableArray;
// Use any cache that implements `Psr\SimpleCache\CacheInterface`
$cache = new \Symfony\Component\Cache\Simple\FilesystemCache;
// Create the CacheableArray instance
$ac = new CacheableArray($cache, 'my_cache_key');
// Use standard PHP array syntax for accessing, counting or iterating over the CacheableArray instance
$ac['key'] = 'value';
echo $ac['key'];
echo count($ac);
foreach ($ac as $k => $v) {
echo $v;
}
unset($ac['key']);
Cache TTL
Default cache TTL is 1 hour. Cache TTL can be defined in seconds by providing a 3rd argument to the constructor or by calling the CacheableArray::setTTL
method:, (*8)
use Serato\CacheableArray\CacheableArray;
// Create a CacheableArray with a cache TTL of seconds
$ac = new CacheableArray($cache, 'my_cache_key', 60);
// Change cache TTL to 300 seconds
$ac->setTTL(300);