Home > Zend Framework > Zend Framework:: Caching the database query results

Zend Framework:: Caching the database query results

Caching is basically used to improve the performance of the application. Your application may consists of multiple expensive queries ruining the application performance.  The Zend_Cache component of Zend Framework provides a good feature to improve the page performance by caching the database query results. Here is the sample code :

// Creating the cache options
$frontend = array(
‘lifetime’ => 86400, // cache lifetime of 24 hours (time is in seconds)
‘automatic_serialization’ => true  //default is false

$cachedir = /path/to/cacheDirectory;

$backend = array(‘cache_dir’ => $cachedir);

// Getting a Zend_Cache_Core object
$zend_cache = Zend_Cache::factory(‘Core’, ‘File’, $frontend, $backend);

$result = run_query($zend_cache);

function run_query($cacheObj){
$q = “Database query”;
if(!$result = $cacheObj->cache->load(“myresult”)){
$db = Zend_Db::factory(DB_connection_parameters);
$result = $db->fetchAll($q);
$cacheObj->save($result, “myresult”);
else {
echo “This result is from cache.”;
return $result;

Caution: You should give the unique name in the “load(‘name’) and save(‘name’)” functions.
Otherwise you will get the same result on the pages where the query is intended to produce
different results.

Categories: Zend Framework
  1. December 11, 2009 at 6:51 am

    I thought I’m gonna use this cache feature in Zend Framework. Good Article!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: