Controlling element caching in CakePHP 2.3

Element caching is critical to site performance if used judiciously.  Sometimes you want more control over the cache expiration than you get automatically.

In CakePHP 1.X, you used to be able to do this as described here:

<?php 
$key = 'my_cached_element';
echo $this->element('my_element', array('cache' => array(
   'time' => $do_update ? '-1 day' : '+1 day',
   'key' => $key
))); 
?>

But not anymore (apparently the fact this worked was a bug); at any rate the “time” parameter is no longer honored.  In fact, looking at the API, there’s no way I can see to dynamically change the cache configuration used by the element (even Config::set() didn’t seem to work as expected).  All you can do is set a previously named config, e.g., “short”.

So if you want to clear the cache you need to do it manually, given the key, as described here.  So this works:

<?php 
// In core.php, name the config and set the duration
Cache::config('short', array(
    'engine' => $engine,
    'prefix' => $prefix . 'cake_short_',
    'path' => CACHE,
    'duration' => '+1 hours',
    [...]
));

// In your view, reference the named config
if ($do_update)
    Cache::delete('element_' . $key, 'short'); 

echo $this->element('my_element', array('cache' => array(
   'config' => 'short',
   'key' => $key
))); 
?>

Seems like this workaround is a bit hacky, so we’ll see if it gets “fixed” too.

Leave a Reply

Your email address will not be published. Required fields are marked *