Quick start

In order to work with cache, you’ll first have to create an instance of the desired cache driver.

$cache = new \Opis\Cache\Drivers\File("/path/to/cache");

Writing content to cache

Writing data to cache can be performed by using the write method.

/**
 * @param string $key Cache key
 * @param mixed $data Cached content
 * @param int $ttl Time to live (optional), use 0 for persistent cache
 * @return bool True if the data was cached
 **/
public function write(string $key, $data, int $ttl = 0): bool;

Examples

// Persistent cache
$cache->write("key-a", "some content");

// Cache for 10 seconds
$cache->write("key-b", [1, 2, 3], 10);

Fetching cached content

The get the cached content for a specific cache key, you can use the read method.

/**
 * @param string $key Cache key
 * @return mixed The cached content or false if the key is not present
 **/
public function read(string $key);

Examples

echo $cache->read('key-a'); //> some content

The read method returns boolean false if no content is present for the specified key, so in some cases you will first want to check if the cache key exists by using the has method.

/**
 * @param string $key Cache key
 * @return bool True if the key exists
 **/
public function has(string $key): bool;

Examples

if ($cache->has('key-a')) {
  echo $cache->read('key-a'); //> some content
} else {
  echo "key-a is not present";
}

However, in most cases you’ll want to generate the cached content if it’s missing. Instead of using a combination of has, read and write you could simply use the load method.

/**
 * @param string $key Cache key
 * @param callable $generator A function that will return the content to be cached
 * @param int $ttl optional, a time to live in seconds for the generated content
 * @return mixed The cached content
 **/
public function load(string $key, callable $generator, int $ttl = 0);

Examples

$numbers = $cache->load('key-b', function () {
    // this function is invoked only if the cache key is missing
    // the return value of this function is saved in cache, using the
    //    specified ttl, in our case 10 seconds
    return [1, 2, 3];
}, 10);

echo array_sum($numbers); //> 6

Deleting cached content

To remove a cached content by key you can use the delete method.

/**
 * @param string $key Cache key
 * @return bool True if the content associated with key was deleted
 **/
public function delete(string $key): bool;

Examples

$deleted = $cache->delete("key-a");

In order to remove all cached content, regardless of key, you can use the clear method.

/**
 * @return bool True if cache was cleared
 **/
public function clear(): bool;

Examples

$cache->clear();