Cache

marcelklehr edited this page Feb 15, 2013 · 5 revisions
Clone this wiki locally

It all begins with the cached item

<?php
$key = 'foo'
$my_item = Zoo\Cache::item($key);
?>

Now you can poke around with the cache entry associated with the key passed to Cache::item:

get returns the cached data associated to $key or FALSE if none is available

<?php
$my_item->get();
?>

Insert/replace contents, passing new cache data as a string to store.

<?php
$my_item->store($new_contents, $time_to_live);
?>

reset forces Zoocache to forget the currently stored data for that key.

<?php
$my_item->reset();
?>

You can also reset all cache entries at once.

<?php
Cache::resetAll();
?>

There is a very handy shortcut method you will use very often, rather than the ones above:

<?php
$comments = Cache::retrieve($key, function() {
  // ...
  // Query the database to retrieve comments -- very expensive
  // ...
  return $comments;
}, $time_to_live);
?>

This method takes a key, a callback and the expiry time. It will firstly try to get the data associated with $key from the cache. If this fails, the callback is invoked. Its return value is stored in the cache with $key and $time_to_live and then passed through.