16/08/2011

Zend Cache

For my API (I'll write a post about that someday) I have a request that involve fetching all jobs that were produce in one year.
As you imagine, this is resource intensive and takes a lot of time to fetch. So it was time to use Zend Cache.
All my previous work is done inside an intranet, and everything is quite snappy, so I never have a chance to use this component from Zend Framework.
I decided to test two types, one with Memcached and the other form file. For my surprise or not the file version is as fast as the Memcache one, at least in this situation. And so I choose the file one. Minus one configuration to do.
As with almost ZF components the Zend Cache is very straightforward to configure.
We´ll start with the Bootstrap configuration:
protected function _initCache()
{
$frontendOptions = array(
'lifetime' => 259200 ,
'automatic_serialization' => true,
);

$backendOptions = array(
'cache_dir' => APPLICATION_PATH . '/../tmp/');


$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

Zend_Db_Table_Abstract::setDefaultMetadataCache($cache);

Zend_Registry::set('API_Cache', $cache);

}

Pretty simple hein!?
We have the configuration of the frontend e backend options. In the lifetime the measure is in seconds. In my case the cache is valid for 3 days. The backend is the dir where the files will be stored.
Now use the factory method to store the options, set the Default Zend_Db_Table MetadataCached for speed gains, and store the cache variable in the registry.
Using the Cache
Below is part of my REST Class
/**
* Cache Object
* @var Zend_Cache
*/
private $cache;

public function __construct()
{
.......
    $this->cache = Zend_Registry::get('API_Cache');
}

.......

if(!($job = $this->cache->load('get3'.$code)))
{
    $prod = $this->embalagem->getJobParamsByClientCode($code);
    foreach ($prod as $value)
     {
       $result['job'.$i]= $this->job($key, $value['obra']);
       $i++;
     }

    $this->cache->save($result, 'get3'.$code);

} else {

    $result = $this->cache->load('get3'.$code);
}

return $result;
.......
What we can see is first we checked if the cache file exist, if not fetch the data from the database and write the cache file.
It´s very simple to use this component and the gains are amazing.
I can tell you, that the non cached version took 22.3969 seconds to process and the cached version took only 1.4055 secs. A tremendous speed gain, with a few lines of code.

No comments:

Post a Comment