Archive

Posts Tagged ‘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
   Zend_Db_Table_Abstract::setDefaultMetadataCache($cache); 
 
   // 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 
$cache->remove($cacheKey);

// clear the entire cache
$cache->clean(Zend_Cache::CLEANING_MODE_ALL);

// clean only outdated
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);

 

Categories: LAMP, Web Development Tags: ,