Page caching in CodeIgniter is an all or nothing affair. Meaning that you either cache a full page or you don't cache anything. This might have been useful in the 90's when websites were far less interactive than they are today. However in the modern age of web design pages often have dynamic content that changes on a per user basis. For instance showing a users name at the top of a page when they are logged in, or providing an administration option if someone has the proper security clearance. These things would cause a page to look different from one user to the next. This simply isn't possible with the default implementation of caching, the last thing we need is having someone without clearance to be able to know more about our sites administration area.
Many people have written caching libraries for CI and I am sure there are some good ones. All of them lack the shear simplicity of CI's implementation, so here is my stab at it.
The name of this library is called scache for s(imple)cache it has one relatively small library file and a config file. If you would prefer you can combine the config file with CI's config file.
This library lets you cache whatever you need whether that be a full page or a small page segment. You define the unique key used to retrieve the cache file.
The library methods are as follows:
$this->scache->clear($key); $this->scache->read($key); $this->scache->write($key);
The clear method should generally be used to clear a cache file if you cannot wait for it to expire normally. Say for example you allow commenting on a page you obviously don't want your users to have to wait several minutes before they can view what they posted. Speaking of expiration, remember that config file I told you about? It only has a single line which defines how long to cache a file in minutes here are its contents:
$config['cache_expiration'] = 1;
Let's see this sucker in action now.
if(!$cache = $this->scache->read($key)) { //Build your view data array here // // // $cache = $this->load->view('page_segment', $data, true); $this->scache->write($key, $cache); } $this->load->view('full_page', array('segment'=>$cache));
Somethings to keep in mind looking at this implementation:
- The key value can be whatever you want, as long as it is always unique to that particular page segment. The key is how the library will name and find the cache file so it needs to be unique.
- In this setup I have a wrapper called "full_page". This file would include things like the main nav the logo the footer etc. Where as "page_segment" is only meant to contain something that will remain static like an 'About Us' paragraph or something.
- Remember the data contained in "page_segment" should not change between users or at least not change much.
http://dl.dropbox.com/u/13081549/Scache.zip