Syntax Sugar #5 - A Quick CodeIgniter Caching Helper Function
Saturday, January 7, 2012 at 5:45PM Caching your data in CodeIgniter? Good. You should be.
I use memcached lots. CI has a fantastic caching driver built in (as of 2.0). Normally, the code you'll write looks like this:
$accounts = $this->cache->memcached->get('user.' . $user_id . '.accounts');
if (!$accounts)
{
$accounts = $this->db->where('user_id', $user_id)->get('accounts')->results();
$this->cache->memcached->save('user.' . $user_id . '.accounts', $accounts);
}
$this->load->view('accounts/index', array( 'accounts' => $accounts ));
However this quickly becomes repetitive, boring and cluttering. With a bit of PHP5.3 magic, we can create a really nice little caching helper function that cleans this code up in no time:
function cache($key, $data) {
$CI =& get_instance();
$cache = $CI->cache->memcached->get($key);
if (!$cache) {
// There's been a miss, so run our data function and store it
$cache = $data($CI);
$CI->cache->memcached->save($key, $cache);
}
return $cache;
}
Now, our cluttered caching code becomes a commendable concoction of coding culinary craft:
$accounts = cache('user.' . $user_id . '.accounts', function(&$ci){
return $ci->db->where('user_id', $user_id)->get('accounts')->results();
});
The anonymous method you pass through will only be executed if the cache misses (i.e. there's no data under that key, or it has expired). It will be saved into the cache and return. Delicious.
codeigniter,
memcached,
syntax sugar 

