Saturday, September 22, 2012

How to cache data using Zend_Cache

Cache is a temporary storage area where frequently used data can be stored for faster access. If we are running a very expensive query to fetch records from the database very frequently, we can store these data in the cache (in our machine memory or file system). Accessing the memory will be quicker than connecting to database and fetching the data.

In Zend Framework, we can achieve this by using the Zend_Cache, it is very flexible such that, it allows you what you want to cache and where you want to cache.

What you want to cache (Frontend)
The main parameters which is used are


This controls whether we need to have caching or not, defaults to true


How long the cache should be alive

Automatic Serialization

defaults to false, if it is set to true, serialization will happen on the fly, if not we must perform it

Where you want to cache (Backend)
Backend is nothing but telling the Zend, where you want to store the cached data.
There are many options available, of them Memcache is relatively faster and easy to implement. But here we will see, how to implement it in the File system.

The main parameter which used for File system


Directory where we need to store the cached data

Lets see how to configure the cache settings in Zend through application.ini

Format will be resources.cachemanager.<NAME>.<OPTION> = <VALUE>
resources.cachemanager.config.frontend.options.cache_id_prefix=CACHE_PREFIX "_"

;For File System
resources.cachemanager.config.backend.options.cache_dir=APPLICATION_PATH "/cache"

;For Memcache

By defining these in application.ini settings, Zend will automatically instantiate an instance of Zend_Cache_Manager and set up a cache that is named "config" with the individual options as specified. We can create a different instances of cache like this with its own configuration settings, for example say the above options will be used for all Configuration related items, suppose if you want to have different configuration for data related items, you have to replicate the above setting with the changed to data. "_" "/datacache"

So now in your Bootstrap, you can get the relevant cache manager instance and store in the Zend_Registry, so that it will be available to you at need

$cacheManager = $this->getPluginResource('cachemanager')->getCacheManager();
$cache = $cacheManager->getCache('config'); 
Zend_Registry::set(self::REGISTRY_KEY_CACHE_CONFIG, $cache);

So you can save the cache data like this
$cach->save($data , $cacheKey);
To reterive the data from teh cache
Happy Programming !!!

No comments:

Post a Comment