Zend Framework: cache everything with Zend_Cache

Task: minimize site’s time load using caching.

Solution: use Zend_Cache. Create folder ‘/application/data/cache’ with 776 rights. In file ‘/public/index.php’ after path set (function ‘set_include_path’) add code:

//// ======= caching code =============
//check if ajax, change GET request to make different cache
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && 
	($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')) {
   $_GET['request_type_'] = 'ajax';
require_once 'Zend/Cache.php';
$frontendOptions = array('lifetime' => 600,
                              'automatic_serialization' => true,
                              'debug_header' => false,
                                   'default_options' => array(
                                   'cache_with_cookie_variables'     => true, //create cache even if cookies presents
                                   'make_id_with_cookie_variables'     => false, //do not create different cache for different cookies
$backendOptions = array('cache_dir' => APPLICATION_PATH . '/data/cache');

$cache = Zend_Cache::factory('Page',

//// ======= end caching code =============

And… that’s it! Enjoy ultimate speed of loading site page. My main page script was loading 160 ms on average, after integrating caching — 70 ms.

What happened?

Zend_Cache consists of two classes collections: front-end and back-end.

Front-end focusing on caching objects like certain code pieces, function’s callback, objects, whole pages. We use last one — Zend_Cache_Frontend_Page — it caches the whole page, using ob_start() and ob_end().

As most attentive readers might notice, for front-end we use some parameters. Most interesting part touch upon cookies and are commented in code. I made this couse nothing but Google Analytics uses cookies, that’s why there is no need to generate cookie for every user. Of course, if you have user login depended content you should use another cache type.

Back-ends focus on cache storage like files, sqlite, memcache etc. We use files (Zend_Cache_Backend_File) to store cache. It’s simple and always enable.