Pular para o conteúdo principal

Basic Usage - PSR-16 Simple Cache

PSR-16 is a standard for cache in PHP with less verbosity than PSR-6.

You can just instantiate the cache engine and use it as you can see below.

Get an element from cache and set if not exists​

<?php
$cacheEngine = new \ByJG\Cache\Psr16\FileSystemCacheEngine();

$result = $cacheEngine->get($key);
if (empty($result)) {
// Do the operations that will be cached
// ....
// And set variable result
$result = "...";

// Set the cache with 60 seconds TTL:
$cacheEngine->set($key, $result, 60);
}
return $result;

Check if an element exists in cache​

<?php
$cacheEngine = new \ByJG\Cache\Psr16\FileSystemCacheEngine();
if ($cacheEngine->has($key)) {
// ...
}

Delete an element from cache​

<?php
$cacheEngine = new \ByJG\Cache\Psr16\FileSystemCacheEngine();
$cacheEngine->delete($key);

Check if the engine is available​

Every engine implements CacheAvailabilityInterface. isAvailable() tells whether the engine can be used right now: the PHP extension is loaded and the server answers (Redis, Memcached), the directory is writable (FileSystem, Tmpfs), the session can be started (Session).

<?php
$cacheEngine = new \ByJG\Cache\Psr16\RedisCacheEngine('localhost:6379');
if (!$cacheEngine->isAvailable()) {
$cacheEngine = new \ByJG\Cache\Psr16\NoCacheEngine();
}

Clear all cache​

<?php
$cacheEngine = new \ByJG\Cache\Psr16\FileSystemCacheEngine();
$cacheEngine->clear();