A simple cache library, implementing the PSR-16 standard using immutable objects.
Caching is typically used throughout an applicatiton. Immutability ensure that modifying the cache behaviour in one location doesn't result in unexpected behaviour due to changes in unrelated code.
Desarolla2 Cache aims to be the most complete, correct and best performing PSR-16 implementation available.
composer require desarrolla2/cache
use Desarrolla2\Cache\Memory as Cache;
$cache = new Cache();
$value = $cache->get('key');
if (!isset($value)) {
$value = do_something();
$cache->set('key', $value, 3600);
}
echo $value;
The following implementation allows you to combine cache adapters.
You can set options for cache using the withOption
or withOptions
method.
Note that all cache objects are immutable, setting an option creates a new
object.
All cache implementations support the ttl
option. This sets the default
time (in seconds) that cache will survive. It defaults to one hour (3600
seconds).
Setting the TTL to 0 or a negative number, means the cache should live forever.
Each cache implementation has the following Psr\SimpleCache\CacheInterface
methods:
Retrieve the value corresponding to a provided key
Retrieve the if value corresponding to a provided key exist
Add a value to the cache under a unique key
Delete a value from the cache
Clear all cache
Obtains multiple cache items by their unique keys
Persists a set of key => value pairs in the cache
Deletes multiple cache items in a single operation
The Desarrolla2\Cache\CacheInterface
also has the following methods:
Set option for implementation. Creates a new instance.
Set multiple options for implementation. Creates a new instance.
Get option for implementation.
Cache objects typically hold a Desarrolla2\Cache\Packer\PackerInterface
object. By default, packing is done using serialize
and unserialize
.
Available packers are:
SerializePacker
usingserialize
andunserialize
JsonPacker
usingjson_encode
andjson_decode
NopPacker
does no packingMongoDBBinaryPacker
usingserialize
andunserialize
to store as BSON Binary
The JsonPacker
does not fully comply with PSR-16, as packing and
unpacking an object will probably not result in an object of the same class.
The NopPacker
is intended when caching string data only (like HTML output) or
if the caching backend supports structured data. Using it when storing objects
will might give unexpected results.
Twitter: @desarrolla2
Twitter: @ArnoldDaniels