Home > LAMP, Web Development > Zend Framework 1 – Simple Caching

Zend Framework 1 – Simple Caching

You can cache data in Zend using the Zend Data Cache.

In the Boorstrap.php file add an _init method to initialize the zend cache

Zend will automatically call all methods in bootstrap that start with _init

protected function _initCache () {
   // check and create zend cache directory if it does not exist
   $zendCacheDir = '/tmp/zend-cache';
   if( ! file_exists($zendCacheDir) ) mkdir($zendCacheDir);
   $frontendOptions = array(
     'lifetime' => 24 * 60 * 60, // cache lifetime of 24 hours
     'automatic_serialization' => true // for objects and arrays 
   $backendOptions = array(
     'cache_dir' => $zendCacheDir // Directory where to put the cache files
   // getting a Zend_Cache_Core object
   // we are doing File caching here. Other options are SQLite DB, Memcached, APC
   $cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);
   // cache database table schemata metadata for faster SQL queries
   // register the cache to zend registry so that we can use it anywhere in the application
   Zend_Registry::set('Cache', $cache);

From your controller, you can then use this

public function getuserAction($userid) {
   // get the cache from the registry 
   $cache = Zend_Registry::get('Cache');
   // check if a cached user object exists 
   $cacheKey = "userid_$userid";
   $user = $cache->load($cacheKey);
   if( $user === false ) { // cache miss
    // get user data from the database 
    $user = $this->getUserFromDatabase($userid); // your custom function to get data from the database 
    // save user to cache 
    $cache->save($user, $cacheKey);
  return $user;

Other things you can do with the cache

// remove a cache 

// clear the entire cache

// clean only outdated


Categories: LAMP, Web Development Tags: ,
  1. No comments yet.
  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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

%d bloggers like this: