Tag Archives: MMCache

A Memcached Zend_Cache

Zend_Cache

Usually Zend_Cache is used to store cache files on the file system, which can be really fast and useful in most of the cases. However there’s a faster cache mechanism and hopefully it’s supported by Zend_Cache as well. This is the Memcached backend.

A Faster Cache

Memcached is a really powerful tool to cache directly into the RAM. First, this tool has nothing to do primary with Zend Framework. It’s a server, usually started on some port, that can be called to store and get things from the memory. This of course is very fast, way faster than the cache in the hard drives.

Zend_Cache and Memcached

Zend_Cache has an interface to work with Memcached which is great as usual. The PHP example of Memcache (note that there are two things Memcache and Memcached, which are slight different) can be found here and as it says:

$memcache = new Memcache;
$memcache->connect('localhost', 11211) or die ("Could not connect");
 
$version = $memcache->getVersion();
echo "Server's version: ".$version."<br/>\n";
 
$tmp_object = new stdClass;
$tmp_object->str_attr = 'test';
$tmp_object->int_attr = 123;
 
$memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";
 
$get_result = $memcache->get('key');
echo "Data from the cache:<br/>\n";
 
var_dump($get_result);

However this can be coded into a Zend Framework style like that:

$frontend = array('caching' => true, 'lifetime' => 1800, 'automatic_serialization' => true);
 
$backend = array(
    'servers' =>array(
        array('host' => '127.0.0.1', 'port' => 11211)
    ),
    'compression' => false
);
 
$cache = Zend_Cache::factory('Core', 'Memcached', $frontend, $backend);

Note that you don’t have the typical “cache_dir”, just because everything’s cached into the memory.

Now you can call the cache as it’s called with the “File” backend interface:

$key = 'mykey';
 
if (($result = $cache->load($key)) === false) {
	// call the slow database query here ...
	// save in $result
 
	$cache->save($result, $key);	
}
 
echo $result