
Caching plays a very important role in websites and web applications. In this tutorial, I will explain how we can start using CodeIgniter caching techniques to improve our web application to a new level. I am assuming you have some knowledge of CodeIgniter basics and have the experience to write simple codes using CodeIgniter standards.
Why Caching?
“I am coding, and my code is working well; why must I implement caching techniques?”
Well, this kind of thinking is natural. To understand the main concern behind this, we will need to come out from the domain of “only coding the functionality” to a little higher level of thinking. The two most important factors are as follows:
Applications Performance: It’s vital because the visitors (your customers) are experiencing whom your application is intended. If your application is giving your users a boring/slow performance result, it’s going to be very noticeable/annoying to them. A faster web application always brings peace to a visitor’s mind.
Reduce Server Overhead: The more your web application/site becomes popular, the more your server has to work. It’s always better to lessen the server’s computing/communication load as much as possible. Otherwise, for overloaded or spike traffic, the server may crash often. You can have a highly configured server to handle this, but it will cost a lot which you don’t need to do at all. As this doesn’t always happen, server capability will often remain unused, thus wasted.
Caching can be a good answer to these. We will see how CodeIgniter caching can help our websites and applications in this regard.
Read The Complete PHP CodeIgniter Tutorials Series By CodeSamplez.com
How Many Different Type Of Caching Can be Implemented?
In a traditional web application architecture, there are a few layers where caching techniques can be implemented, such as:
- Browser caching
- View page caching
- Object caching
- Database caching
Luckily, most of them can be controlled by your server application. Let’s examine each one.
CodeIgniter Cache Control Technique For Browser:
By default, web browsers do cache the results that our server generates. Here, we can tell the browser not to cache. Usually, we won’t want to prevent the browser from caching except for some special cases where our outputs are updated very often. So, instead of setting these commands as global/base controllers, let’s practice using them only in the controllers/controller functions where they are needed. You can use the following code snippets only when you want to prevent caching for browsers:
$this->output->set_header("Cache-Control: no-store, no-cache, must-revalidate");
$this->output->set_header("Cache-Control: post-check=0, pre-check=0");
$this->output->set_header("Pragma: no-cache");
Code language: PHP (php)
CodeIgniter Caching For View Pages:
OK, so let us move one level deeper. We now want to cache the output CodeIgniter is generating for visitors. That means. The result of ‘controller function+view code’ combined. Well, if you are using any third-party view renderer, such as the Smarty template engine, you don’t have to worry; it will take care of the view caching. CodeIgniter’s internal support is very helpful if you are not using any. Use the code example below in the controller function where you want caching:
function my_controller_function()
{
//your controller codes goes her.....
$this->output->cache(n);
//n = number of minutes to cache output
//your controller codes goes here....
}
Code language: PHP (php)
Notice that I have mentioned in the code that you can set this anywhere in your controller function. It doesn’t matter where you place it; it will cause the entire controller’s functionality to be cached. Check out CodeIgniter documentation on web page caching for more details.
CodeIgniter PHP Objects Caching:
Well, now we are about to use some advanced-level CodeIgniter caching techniques. Codeigniter can internally interpret with other third-party cache drivers to get the most out of your application. This usually includes support for APC, Memcache, and file/disk-based cache. All your caching code will be similar; you just need to change the driver identifier to the proper one. It makes it very easy/efficient to switch between cache drivers.
Should we move the application to a new server that doesn’t support any caching?
Well, you might be wondering what we will do in such cases. Would we change the code to disable all cache? No, we won’t need to. For this purpose, Codeigniter supports “Dummy Cache” mode. It doesn’t cache anything, really, but your code can be unchanged. Isn’t it cool?
Let’s see a simple use of PHP object caching in Codeigniter. A typical caching code snippet would be as follows:
function my_function()
{
if ( ! $cache_data = $this->cache->get('cache_key'))
{
//here goes your codes...
$some_object = (object) NULL;
$some_object->test_property = "test date";
// Save into the cache for 2 minutes
$this->cache->save('cache_key', $some_object, 120);
$cache_data = $some_object;
}
return $cache_data;
}
Code language: PHP (php)
Whenever the above function is called, it will return data from its cache for up to 2 minutes, and the cache will expire. Then, it will execute all the logic you entered to generate new objects. Depending on your requirements, this can be placed anywhere inside controller functions, model functions or libraries. Check Codeigniter documentation on the caching library for more in-depth knowledge.
CodeIgniter Caching For Database Results:
Yeah, Codeigniter does provide a very nice way to cache the database query results as well! It’s very helpful to balance the load on your database by caching the ‘most frequently used’/’less frequently updated’ database contents. If you are using some third-party database abstraction layer such as doctrine ORM with CodeIgniter, then you won’t need to worry about this level of caching as they have already provided it. But, if you are not and are using CodeIgniter active record or so, then you can use this caching technique to boost the performance of your application.
Luckily, using this is also as simple as other CodeIgniter functionality. We need to provide a command to cache results when we are performing some database operations:
$this->db->cache_on();
$result1 = $this->db->query("SELECT * FROM some_table");
$this->db->select("id");
$this->db->from("some_table");
$result2 = $this->db->get();
Code language: PHP (php)
As soon as we instruct to cache ‘on,’ it will start caching all the results following it. If you need somewhere to disable caching, just use the ‘cache_off’ function before the execution. See complete documentation on database caching for more information.
I hope this brief CodeIgniter caching tutorial will help you understand and improve your web application to be more robust/scalable. Do not hesitate to ask if you have any questions/comments. Happy coding 🙂
Discover more from CODESAMPLEZ.COM
Subscribe to get the latest posts sent to your email.
excelent!
Keep writing!! full of benefit !!
great job….but I have question
What is different between object caching in model function and caching for database results?
very useful. Thanks 🙂
Thanks for such a good information.
A very good summary! Thanks!
Thank for good tutorial.
But I have one problem in cahing file. When I update template, Cache didn’t update. It update when cache time expire.
Please help me how can I update cache when I update template.
Thanks
thanks dude
nice…..but it doesnt privide the cache time…..sometimes some data regulary inserted like 1 hour….
Caching for View pages is kind a confusing though. 🙁
Thank you so much! This helps me a lot. 🙂 Keep writing.
nice article. I have used for one of my website
thanks
Need More clarification on caching!. can you brief?
easy to understand ci about cache
This is very nice article.
I have learn new feature of CI from this article.
But i am confused that how actually implement this concept in code.
It will be more useful if it provides example with proper controller, model and view file
How can I make Codeigniter CSRF protection work when page caching and captcha are used?
Hi there, if I put into my code
$this->db->cache_on();
For the first time while clicking on navigation, page load time is high and the second time same navigation link when visited doesnt take time .Can you help why is it so ?