TomNomNom.com

Blogging since 2008 until 2010

An improved generic caching function

You may remember my generic caching function from a while back.

One of the things I struggled with a little bit was coming up with a key for anonymous functions. I ended up using the SPL ReflectionFunction class to come up with a unique hash for a function and argument list. I happened upon a better solution earlier today: spl_object_hash(). Because PHP's anonymous functions are actually an instance of the (internal) Closure class, they can be hashed no problem.

Here is the updated function:

<?php
function createCached($fn$ttl = 100){
    return function() use($fn$ttl){
        $args = func_get_args();
        if (!is_string($fn)){
            $key = md5(spl_object_hash($fn).serialize($args)); //This is the bit that's changed
        } else {
            $key = md5($fn.serialize($args));
        }
        $result = apc_fetch($key$success);
        if ($successreturn $result;
        $result = call_user_func_array($fn$args);
        apc_store($key$result$ttl);
        return $result;
    };
}

Usage remains exactly the same.

First posted: Thu, 29 Jul 2010 14:00:02 +0000