Caching with Zend_Cache
Caching with PHP is the best way to speed up your application and it’s quite easy thanks to native PHP modules such as APC or output buffering control. It’s even much much easier when you are using the Zend Framework as it contains a native class just for caching – Zend_Cache. To use the Zend_Cache you must first initialize it in the bootstrap and add it to the registry so you can access it easily in controllers, I do it like this:
-
protected function _initCache()
-
{
-
$frontend = array('lifetime' => 7200,
-
'automatic_seralization' => true);
-
// where are we going to stored the cached files?
-
$backend = array('cache_dir' => 'cache');
-
$this->cache = Zend_Cache::factory('core',
-
'File',
-
$frontend,
-
$backend);
-
}
-
-
protected function _initRegistry()
-
{
-
$this->registry = Zend_Registry::getInstance();
-
$this->registry->cache = $this->cache;
-
// I store much more in the registry, of course
-
// for instance, configuration and db adapter
-
}
The frontend and the backend adapters can take much more arguments, read the documentation to learn all possible options. I initialized the Zend_Cache object with the factory method. First argument means that we want to use the Zend_Cache_Core frontend which is the core of the Zend_Cache module. The second argument is the backend we want to use the Zend_Cache_Backend_File backend or that we want to store cached data as files in a specific directory. The other two parameters are frontend and backend options.
Now we can easily access the cache object in controllers or models:
-
$cache = Zend_Registry::get('cache');
-
// does the cache contain data we are looking for?
-
if (!$result = $cache->load('myUniqueId')) {
-
// if not let's cache the data
-
// here I use only a random array but in a real application
-
// you would probably cache some database entries
-
$data = array('John Doe', 'Jane Doe', 'Baby Doe');
-
// besides unique cache id you can use tags to categorize data
-
$cache->save($data, 'myUniqueId', array('tag1', 'tag2'));
-
} else {
-
// dump the cached data
-
var_dump($result);
-
}
That was easy, wasn’t it?
Cleaning the cache
You will surely also want to remove cached files at some point in your application:
-
// clean all cached files
-
$cache->clean(Zend_Cache:: CLEANING_MODE_ALL);
-
// clean only outdated cached files
-
$cache->clean(Zend_Cache::CLEANING_MODE_OLD);
-
// remove a particular cache id
-
$cache->remove('myUniqueId');
-
// remove records tagged as "tag1" AND "tag2"
-
$cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_TAG,
-
array('tag1', 'tag2'));
-
// remove records tagged as "tag1" OR :tag2"
-
$cache->clean(Zend_Cache::CLEANING_MODE_MATCHING_ANY_TAG,
-
array('tag1', 'tag2'));
-
// remove records NOT tagged as "tag1" or "tag2"
-
$cache->clean(Zend_Cache::CLEANING_MODE_NOT_MATCHING_ANY_TAG,
-
array('tag1', 'tag2'));
That’s it for today and, by the way, Merry Christmas
