A couple of years ago Ponderwell built a site on Zend Framework (ZF) as a bit of fun. It’s been moderately successful, getting a steady flow of traffic, but every now and then it catches people’s imagination and gets a huge spike of traffic which makes the server fall over. We needed caching.
ZF has a very simple powerful cache class. You can cache pretty much anything and index it any way you want and store it in memory or the database or as text files. The point of failure when the site got a traffic spike seemed to be MySQL, so I wanted to cache the page data creation in the indexController. The model for a post pulled everything into a single object, so that made things easy. I identified the parameters (post name, sort order) which are passed in to the model to pull the correct post and its ancillary data, and made a key string out of them. That will then index the cache. If the index exists, use the cached version. If it doesn’t, call the model to create the data and save it to the cache before proceeding as normal.
The code is here:
$controller_cache_id = 'front_' . $post . '_' . $sort;
if( false === ($sortedPost = $cache->load($controller_cache_id)) ) {
$sortedPost = new Model_SortedPost($post, $sort);
$cache->save($sortedPost, $controller_cache_id);
}
$this->view->post = $sortedPost->getPost();
$this->view->nextlink = $sortedPost->getNext($sort);
$this->view->prevlink = $sortedPost->getPrev($sort);
…. etc.
To set up the cache ($cache, above) do something like this:
$frontendOptions = array(
'lifetime' => 7200,
'automatic_serialization' => true
);
$backendOptions = array(
‘cache_dir’ => realpath(APPLICATION_PATH . ‘/../cache’)
);
$cache = Zend_Cache::factory(‘Core’, ‘File’, $frontendOptions, $backendOptions);
That’s all there is to it. Make sure /cache/ is writable by Apache. I’ll do some testing and let you know how well it works.