No posts in a while huh! Been pretty busy and haven't thought of much to blog about lately. But I've been playing with Memcache and wanted to share a tiny class I made to add easy caching to my PHP projects. This PHP class just provides a nice simple interface to use by extending the Memcached class:

// Call the class whatever you want
class MyCache extends \Memcached {
    function cache($key, $time, $func) {
        if (($val = $this->get($key)) === false) {
            $val = $func();
            $this->set($key, $val, strtotime($time) - time());
        return $val;

And now to use it, first you summon it in the same way as the regular class:

$c = new MyCache;
$c->addServer('', 11211);

Then where you would like to begin caching (I'm using this very blog as an example, where GeSHi for syntax highlighting is the main bottle-neck for page generation), you call the class like so:

// Example using my BLACK blog engine (

// Here is the original line
$row['body'] = render($row['body']);

// And here is a cached version
// As you can see we have a KEY, a TIMEOUT, and a FUNCTION to call for a cache miss
$row['body'] = $c->cache("blog_post_{$row['id']}", '30 minutes', function () use ($row) {
    return render($row['body']); // Renders all the post filters, including syntax highlighting

Awesome, for this small tweak on my local test blog (with 4 posts), this takes the page response time down from 14ms to 2ms. Quite a win I'd say :)

Of course this code requires the memcached PHP extension and a running Memcache server ;)

(Maybe) Related posts: