I wanted to create a class to cache dynamic PHP output (or a portion of it from one page) using Memcached key/value story. Basically it checks to see if the file has been cached already, if it has, it grabs it from Memcached and spits it out, otherwise, it outputs the file and stores it in Memcached for three hours.
The purge function loops through all the keys in Memcached (because I also use Memcached for other things and "flush" won't work) and pulls out all the keys starting with "cache_" and removes them. I run this whenever I have completed database updates.
I was looking for feedback on this class -- for those more talented than me to point out issues with the code -- and also thought others might be interested in it if others thought it was of legitimate value.
Following is the class:
class MemcachedCache
{
var $objMemCached;
var $strCacheKey;
var $boolTimeStamp = true;
var $intCacheTime = 10800; //three hours
var $boolCaching = false;
function __construct()
{
$this->objMemCached = new Memcached;
$this->objMemCached->addServer('localhost', 11211);
$this->strCacheKey = 'cache_' . base64_encode($_SERVER['REQUEST_URI']);
}
function start()
{
if(!($result = $this->objMemCached->get($this->strCacheKey)))
{
$this->boolCaching = true;
ob_start();
}
else
{
echo $result;
exit;
}
}
function end()
{
if ($this->boolCaching)
{
$data = ob_get_contents();
if ($this->boolTimeStamp)
$data .= '<!-- Memcached at: ' . date('Y/m/d H:i:s') . ' -->';
$this->objMemCached->set($this->strCacheKey, $data, $this->intCacheTime);
ob_end_flush();
}
}
function purge()
{
$arCachedKeys = $this->objMemCached->getAllKeys(); //get all the keys in the db
foreach($arCachedKeys as $strKey) //loop through each one
{
if (substr($strKey, 0, 6) == 'cache_') //for all of the player date keys
$this->objMemCached->delete($strKey); //delete the date key
}
}
Following is an example of how it could be implemented:
$cache = new MemcachedCache();
$cache->start();
//PHP output here
$cache->end();