Darrin's Tech Ramblings

Using Zend Cache to save the results of a function

Advertisements

The Zend_Cache is a great way to save (i.e. cache) the results of a function. Using ->call() it will automatically handle building a unique key for each cache based on the arguments passed to the function. So, all you have to do is ->call() the function and use the results as you normally would.

The following example caches the results of calling the getData function in the CustomStats class. The cache automatically expires after 120 seconds which results in the getData function being run only once every other minute.

$class_name    = 'CustomStats';
$function_name = 'getData';

try {
    $cache = Zend_Cache::factory('Function', 'File', array(
        'caching'                 => true,
        'lifetime'                => 120,   // 120 seconds
        'cache_id_prefix'         => $function_name,
        'automatic_serialization' => true
    ), array(
        'cache_dir'               => APPLICATION_PATH."/cache/",
        'hashed_directory_level'  => 2,
        'hashed_directory_perm'   => '0755',
        'cache_file_perm'         => '0644'
    ));

    if ($class_name) {
        $results = $cache->call(array($class_name,$function_name), 
                                array($param1,$param2,$etc));
    } else {
        $results = $cache->call($function_name, 
                                array($param1,$param2,$etc));
    }

} catch(Zend_Cache_Exception $e) {

    // Don't blowup if Zend_Cache fails ... 
    // ... just put a message in the log and continue.
    trigger_error($e->getMessage(), E_USER_NOTICE);

    $results = false;
}

print $results;

Advertisements