Chapter 2. Zend_Cache

Table of Contents

2.1. Introduction
2.2. Zend_Cache factory
2.3. Zend_Cache_Core
2.3.1. Introduction
2.3.2. Available options (for this frontend in Zend_Cache factory)
2.3.3. Examples
2.3.4. clean the cache
2.4. Zend_Cache_Output
2.5. Zend_Cache_Page
2.6. Zend_Cache_File
2.7. Zend_Cache_Function
2.8. Zend_Cache_Class
2.9. Available backends for Zend_Cache
2.9.1. Zend_Cache_Backend_File
2.9.2. Zend_Cache_Backend_Sqlite

2.1. Introduction

Zend_Cache provides a generic way to cache some datas.

Cache records are stored through a backend (File, Sqlite...) with a flexible system of "ids" and "tags". Then, for example, it's easy to delete a specified part of cached datas ("all cache records marked with a given tag"...).

The core of the module is really generic and flexible. Yet, for specific needs, you can use a frontend (Output, Function...) to get a more appropriate way of running.

Example 2.1. A first example with Zend_Cache core

In this first example, we will use directly the core of Zend_Cache with the File backend.

<?php
require_once 'Zend/Cache.php';

$frontendOptions = array(
	'lifeTime' => 7200 // cache lifetime of 2 hours
);

$backendOptions = array(
    'cacheDir' => '/tmp/' // Directory where to put the cache files (make sure to add a trailing slash)
);

// We make a Zend_Cache_Core object
$cache = Zend_Cache::factory('Core', 'File', $frontendOptions, $backendOptions);

$id = 'foo'; // cache id of "what we want to cache"

if (!($cache->test($id))) {
	// cache missed
	
	// require_once ... for perfs reasons, all "require_once" have to be loaded ONLY if the cache is missed
	// require_once ...
	
	// we build "what we want to cache"
	// for example
	$data = '';
	for ($i=0;$i<10000;$i++) {
		$data = $data . $i;
	} 
	
	// We save the result into the cache
    $cache->save($data);

} else {
	// cache hit
	
	$data = $cache->get($id);

}

// do something with $data :)
// [...]
?>       

[Note] Note
With Zend_Cache_Core, you have to manage the "cache identifier" by yourself.