PHP caching

I started to implement the PHP caching for one of my site. Since I use PHP/Smarty, there are a few options.

Smarty offers a page level caching.

You can cache the entire page with Smarty’s caching capability. It is very easy to use. Just specify the $smarty->caching attribute and the whole page will be cached. The only downside I see is its inflexibility to cache the data in a more granular level. With a complicated database driven backend, we need to deal with different type of information we pulled from the database and decide whether to cache or how long to cache.

The Cache_Lite from PEAR is a great PHP lib to do this. It can take a String and cache it to a file, or talk a more complicated object and serialize it then cache it. Or you can use the serialize() /unserialize() method directly, like the way its done in the following code.

A “wrapper” class can be created to suite the need for caching different type of data:

require_once PEAR_DIR . “Lite/Cache/Lite.php”;
class CacheUtil {
private $cLite;
private $group;
function __construct($type = 0) {
// Set a few options
$options = array(
‘cacheDir’ => CACHE_DIR,
‘lifeTime’ => 3600
);
switch ($type) {
case TYPE_0:
$options['cacheDir'] = CACHE_DIR . “type0/”;
$options['lifeTime'] = 3600*24; // cache 1 day
$this->group = “type0″;
break;
case TYPE_1:
$options['cacheDir'] = CACHE_DIR . “type1/”;
$options['lifeTime'] = 60;
$this->group = “type1″;
break;
}
// Create a Cache_Lite object
$this->cLite = new Cache_Lite($options);
}
/*
* Takes an object needs to be cached, serialize it and store in the CacheLite
*/
public function set($cacheContent, $id) {
if (USE_CACHE == 0) {
return false;
}
$this->cLite->save(serialize($cacheContent), $id, $this->group);
}
public function get(&$cacheContent, $id) {
if (USE_CACHE == 0) {
return false;
}
if ($data = $this->cLite->get($id, $this->group)) {
$cacheContent = unserialize($data);
return true;
} else {
return false;
}
}
public function remove($id) {
if ($this->cLite->get($id, $this->group) !== false) {
$this->cLite->remove($id, $this->group);
}
}
public function clean() {
$this->cLite->clean($this->group);
}
public function nuke() {
$this->cLite->clean();
}
}
 Â

While using caching can definitely help speeding up the data retrieval if there is database involved, it also adds the complication to the code, for example: whenever there is any type of insert/delete/update, the cache will also need to be flushed if affected; caching is not free, it takes up the file system space too, therefore, a backend console for monitoring the caching usage is also needed to be considered.

This entry was posted in PHP development. Bookmark the permalink.