19 September 2010

This tutorial shows you how you can cache code in CodeIgniter, by saving string or plain text into a file.

Caching is essential in PHP. CodeIgniter has built-in class for it aswell, but that caches views only. But for shorter codes I find using views makes it harder to get your head around it, so write everything in controlls.
First pick a folder for storing your files. I made tmp folder to my root dir. Then make a file in there and call it codeigniter_cache.html. You also have to give it all permissions(777) so it would be writable. We use file helper for writing and reading files.

Update function:

This functions deletes old code and put new in it. You should call this function every time the cached code would generate different result. If you have cached menu then you would like to update it when menu items are changed.
Source code viewer
  1. function update_cache($text){
  2. $this->load->helper('file');
  3. if(!write_file('./tmp/codeigniter_cache.html', $text))
  4. return 'Cache file wasn\'t updated!';
  5. else
  6. return 'Cache file was successfully updated!';
  7. }
Programming Language: PHP

Read function:

This function should get cached code from file. This code is actually only 2 lines so you don't even have to put it in a function.
Source code viewer
  1. function read_cache(){
  2. $this->load->helper('file');
  3. return read_file('./tmp/codeigniter_cache.html')
  4. }
Programming Language: PHP
As you can see you can store any values. If you want to store somethign else than plain text then you have to make a bit more complex read and update functions, but my point is that the possibilites of caching are endless. You have completed our codeigniter cache tutorial.