Increasing dynamic web site performance with Zend Framework and Memcached
Using a good solution to cache your web application can increase the performance by 70%.
There are several good PHP caching solutions however, in this example we are going to use the Zend Framework Cache system with the power of Memcached.
What is memcached?
The Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
Getting started.
So in the same way that we include any Zend Framework packages we need to include the Zend/Cache.php. Follow an example code:
<?php
require_once 'Zend/Cache.php';
$frontendOptions = array('lifeTime' => 20);
$backendOptions = array(array('host' => 'localhost','port' => 11211, 'persistent' => true));
$cache = Zend_Cache::factory('Core', 'Memcached', $frontendOptions, $backendOptions);
if (!$result = $cache->get('time') ){
$time = date('r');
echo "generated: " . $time;
$cache->save($time, 'time');
} else {
echo "cache hit: ". $cache->get('time');
}
?>
In the first 3 lines of this example we created our instance of the Zend_Cache class and configured the frontend and backend driver:
require_once 'Zend/Cache.php';
$frontendOptions = array('lifeTime' => 20);
$backendOptions = array(array('host' => 'localhost','port' => 11211, 'persistent' => true));
The frontend specifies only the lifetime that the cache data must be valid. For the Backend options we have to set up the localhost, the port and whether the daemon of memcached must be persistent.
The rest of code simply set and get a cached data.
Zend_Cache uses a modular approach to specify the frontend and backend drivers. The frontend driver determines what data is gathered and from your PHP script. The backend driver determines how the data is stored. In this example we are using the "Core" frontend driver, which is the top-level frontend driver which provides functionality that all other frontend drivers inherit. The "Memcached" backend driver provides memcached-based storage for your cached data.
In conclusion
The cache system can boost a lot the performance of your Ajax based application.
Using a memory based backend driver will speed up your code cache execution since the filesystem will not need to be touched during the execution of your scripts. Using memcache you will also be able to share your memory between machines enabling a cluster of machines to share the same cache.
There is also no support for SHM or database backends, and the frontend drivers available are not as numerous or mature as other Cache systems (such as PEAR::Cache).
