serato / cacheable-array
Provides an array-like object whose contents are persisted to a PSR-16 cache
Installs: 27 928
Dependents: 0
Suggesters: 0
Security: 0
Stars: 0
Watchers: 15
Forks: 8
Open Issues: 0
Requires
- php: ^7.1 || ^8.0
- psr/simple-cache: ^1.0.0
Requires (Dev)
- phpstan/phpstan: ^1.4
- phpunit/phpunit: ^7 || ^8
- squizlabs/php_codesniffer: ^3.0
- symfony/cache: ^3
README
Provides an array-like object whose items are persisted to a PSR-16 cache instance.
Upon creation the object is populated with existing items from the cache, should they exist.
Items are saved into the cache when the instance is destroyed.
Note: No attempt is made to synchronise multiple instances of CacheableArray that use the same cache instance and cache key.
Requirements
- PHP 7.1 or above
Installation
Installation will usually consist of adding the library to a project's composer.json
file:
{ "require": { "serato/cacheable-array": "^1.0" } }
Usage
Create a Serato\CacheableArray\CacheableArray
instance by providing a Psr\SimpleCache\CacheInterface
instance and a cache key:
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:
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);