Here's my latest update to the caching function to make things even easier. Simply specify a cache key and a callback function - if the data exists in the cache, it will be fetched. Otherwise, the callback will be called and the returned data will be stored in cache and returned to the user.
PHP Code:
/**
* Attempts to fetch key from the cache. On failure,
* calls the callback and stores the data
*/
public function fetch($key, $callback, $time = 3600)
{
$data = $this->memcache->get($key);
if (!$data)
{
$data = call_user_func($callback);
$this->memcache->add($key, $data, $time);
}
return $data;
}
Usage:
$cacheobj->fetch('data_key', 'some_function');
See php's documentation on call_user_func for more info on what $callback can contain.