CodeIgniter sure is one kick-ass framework. The built-in cache functionality is great for scaling your app. Unfortunately you can’t manually expire your cache. Why would you want to do that? Let’s presume you have a pretty Read-heavy site delivering different articles to the public. Since every user, logged in or not, will see the same article this a good place to cache. But, if the author changes his article, you want to update the cache file as well. Otherwise the output will contain the old output until it automatically expires. In some cases this would be just fine, but let’s presume you’re building a news site and need your articles to be up to date immediately. This is where you’ll need to manually expire your cache. To do so, you’ll have to extend the CI_Output class. Create the file ‘system/application/libraries/MY_Output.php’
<?php class MY_Output extends CI_Output { function expire_cache($uri) { $this->_expire_cache($uri); } function _expire_cache($uri) { log_message('debug', 'Deleting cache for '.$uri); // Get the instance $CI =& get_instance(); // Load the cache directory from the config file $path = $CI->config->item('cache_path'); // If no value is specified, use the standard cache path $cache_path = ($path == '') ? BASEPATH.'cache/' : $path; // Generate the file name $file = $CI->config->item('base_url'). $CI->config->item('index_page').'/'. $uri; // md5 hash of the cache item $cache_path .= md5($file); // try to delete it if(@unlink($cache_path)) { log_message('debug', 'Deleted the cache for '.$uri); return; } else { log_message('error', 'Unable to delete the cache for '.$uri); return; } } }
CI’s built-in cache uses a hash of the page’s URI to name the cache file, so you’ll need to pass that URI to the expire function. Normally your URI will be ‘controller/method’.
To expire your cache you can now use the following code within your controllers:
$this->output->expire_cache('controller/method');