Caching

You might it useful to cache data structures that are large or take a long time to calculate on the disk. Enano uses a caching system that reads in an entire file using include(), making it possible to load cached data structures with thousands of values literally in microseconds on servers that use PHP opcode caches like eAccelerator.

The $cache global object is an instanciation of the CacheManager class. It contains three methods: store, fetch and purge. Data being cached can theoretically be of any type besides an object, but the most common type (and the only type that is tested) is array.

Storing data

You can store a value in the disk cache using the $cache->store() method.

bool $cache->store(string $cache_id, mixed $data, int $ttl = 20)

$cache_id should be a name for what you are caching. It may consist only of the letters a-z (lowercase only), 0-9, and underscores. You'll need to pass this value back to the fetch or purge methods. $data should be the value you are storing, and $ttl should be the time, in minutes, until the cached item expires. If $ttl is set to -1, the cached item will expire only when purged manually. Note that if caching is disabled site-wide, this function will silently ignore the request and return false.

Example

global $cache;
$data = calculate_enormous_dataset();
// Expire it in 60 minutes
$cache->store('my_big_dataset', $data, 60);

Retrieving data

Just call the fetch() method.

bool $cache->fetch(string $cache_id)

Returns the data structure you stored with $cache->store(), or false if the item couldn't be found or is expired.

Example

global $cache;
if ( !($data = $cache->fetch('my_big_dataset')) )
  $data = calculate_enormous_dataset();
 
// $data now most certainly contains what we're looking for.

Purging data

Pretty much just as straightforward:

bool $cache->purge(string $cache_id)

If the given cache exists, this method deletes it. You should be calling this whenever your data changes in the database, so that changes are seen immediately.

Example

$cache->purge('my_big_dataset');

Categories: (Uncategorized)