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
function update_cache($text){ $this->load->helper('file'); if(!write_file('./tmp/codeigniter_cache.html', $text)) return 'Cache file wasn\'t updated!'; else return 'Cache file was successfully updated!'; }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
function read_cache(){ $this->load->helper('file'); return read_file('./tmp/codeigniter_cache.html') }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.