How to disable codeigniter’s cache

Learn how to disable Codeigniter’s cache for some specific IP address or logged in users and how to implement your own cache logic.

Enabling the Codeigniter’s cache

Enabling the cache is very easy in your Codeigniter’s application. In any of your controller when you want it enabled just call this function:

$this->output->cache($minutes);

when your controller finishes the output from the views is generated to both the browser of you users and also stored into the cache directory onto the filesystem.

The drawback of the Codeigniter’s cache

After a controller output has been cached the behavior of the Codeigniter’s cache system it’s not what you may have expected. Indeed when a cached copy is present onto the filesystem and the cache timeout has not yet expired then this static cached copy is served before your controller gets called completely bypassing any of your controller’s logic.

While providing great performance, my websites dropped from 2 seconds to 0.01, it has the drawback that you cannot implement any cache logic you wish into your controllers. This is because the function call:

$this->output->cache($minutes);

it’s just to enable the saving onto the disks of the controller’s view output; while, the checking about the rendering or not of the cached version of your URLs, it’s done way before the controller logic gets called.

Disabling the Codeigniter’s cache for some IP address or logged in users

In many circumstances you don’t want to have this feature and, particularly, when you want that some IP address, like your office, or some logged in users, needs to have fresh dynamic content to be served instead of the static content copy from the Codeigniter’s cache.

To implement this kind of cache logic in Codeigniter is quite easy: you have to override the core’s Output class.

Just follow those instructions:

1) create a new class file

In order to do that create a core directory under your application directory, and create a new class file called MY_Output.php the result must be ./application/core/MY_Output.php.