-
Notifications
You must be signed in to change notification settings - Fork 286
Caching
If you're running any page that doesn't fully require dynamic content, it might be in your best interest to cache the page. Especially in high request projects or environments.
Some things to keep in mind when caching.
- Avoid doing any "tickers" for page counts or anything of that sort. They won't work with caching and to put it simply, its really not worth the performance downgrade.
- If you do "page" type caching, you have to consider that you cannot clear this cache dynamically. You would want to use the "memory" caching tool if you want to do this.
All you need to do is add this one line in.
$this->output->cache(n);
Where n
is the number of minutes you'd like to keep the cache for. If you don't want to use the cache anymore, simply just get rid of that line.
You will need to note that CodeIgniter will keep this cache based on the input of the URL. For example controller/function/var1
will cache differently to controller/function/var2
.
You must use CodeIgniter "views" in order for this to work properly.
Memory caching is much more dynamic. In fact, I would suggest optimizing your models using this. Since this type of caching can be much more complicated, I'll show a brief example.
function retrieve($id)
{
if (!$data = $this->cache->get($id))
{
// run some processing here
$data = $this->database->get('some_table');
// store data into memory using
$this->cache->save($id, $data, 86400); // last param is time in seconds
}
return $data;
}
From here, we will try to ping the cache for data and try to place it in $data
if not, we will have to run our primary functions. When the primary functions are done, we'll save it to the cache.
If you're really daring, you should take a look at the CodeIgniter documentation on how to load the caching class with APC or Memcached.