• Skip to main content
  • Skip to primary sidebar
  • Skip to footer
  • Home
  • Featured
    • C# Tutorials
      • LinQ Tutorials
      • Facebook C# API Tutorials
    • PHP Tutorials
      • CodeIgniter Tutorials
    • Amazon AWS Tutorials
  • Categories
    • Programming
    • Development
    • Database
    • Web Server
    • Source Control
    • Management
    • Project
  • About
  • Write
  • Contact

CodeSamplez.com

Programming, Web development, Cloud Technologies

You are here: Home / Development / How To Work With Codeigniter Caching In PHP

How To Work With Codeigniter Caching In PHP

January 22, 2013 by Rana Ahsan 17 Comments

Codeigniter Caching Tutorial

For websites/web applications, caching plays a very important role. Today, 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 CodeIgniter basics knowledge already and have the experience to write simple codes using Codeigniter standards.

Why Caching?

codeigniter caching


“I am coding, and my code is working well; why do I need to 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 it, to whom your application is for. If your application is giving your users a boring/slow performance result, it’s gonna be a lot noticeable/annoying to them. The 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 more. 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, most of the time, server capability will remain unused, thus wasted.

Caching can be a good answer to these. We will see how CodeIgniter caching can help in these regards to our websites/applications.

 

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 dig into them one by 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 controller, let’s practice using it only in the controllers/controller functions where it’s 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:

web cache workflow


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 render-er such as smarty template engine, then you don’t have to worry at all; it will take care of the view caching. If you are not using any, then CodeIgniter’s internal support is very helpful. 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 in any place of your controller function. It doesn’t matter where you place it; it will cause caching of the entire controller’s functionality. Check out CodeIgniter documentation on web page caching for more details descriptions.

CodeIgniter PHP Objects Caching:

Well, now we are about to use some advance 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 will have to change the driver identifier to the proper one. It makes it very easy/efficient to switch between cache drivers.

Moving the application to a new server which 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 has support for “Dummy Cache” mode. It doesn’t cache anything, really, but your code can be unchanged. Isn’t it cool?

Let’s see 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 then the cache will expire. Then it will execute all logic you entered to generate new objects. This can be placed anywhere inside controller functions, model functions or libraries, depending on your requirements. Check Codeigniter documentation on 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 kind of third-party database abstraction layer such as doctrine ORM with CodeIgniter, then you won’t need to worry about this level of caching as it’s already provided by them. 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 just 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 🙂

Share If Liked

  • Click to share on Facebook (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Click to share on Pocket (Opens in new window)

You may also like

Filed Under: Development Tagged With: cache, codeigniter, php

About Rana Ahsan

Rana is a passionate software engineer/Technology Enthusiast.
Github: ranacseruet

Reader Interactions

Comments

  1. necoide says

    May 24, 2013 at 7:55 pm

    excelent!

    Reply
  2. oriza says

    August 6, 2013 at 4:46 pm

    Keep writing!! full of benefit !!

    Reply
  3. ahmed elgendy says

    November 24, 2013 at 12:03 pm

    great job….but I have question
    What is different between object caching in model function and caching for database results?

    Reply
  4. stipica says

    March 3, 2014 at 7:05 pm

    very useful. Thanks 🙂

    Reply
  5. Amar Jit Attri says

    November 26, 2014 at 5:28 am

    Thanks for such a good information.

    Reply
  6. Peter says

    November 28, 2014 at 6:43 am

    A very good summary! Thanks!

    Reply
  7. John says

    December 15, 2014 at 12:31 pm

    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

    Reply
  8. Jidulal says

    December 27, 2014 at 6:39 am

    thanks dude

    Reply
  9. rokcy says

    May 6, 2015 at 9:51 pm

    nice…..but it doesnt privide the cache time…..sometimes some data regulary inserted like 1 hour….

    Reply
  10. aaasdddddnonymous says

    May 28, 2015 at 9:06 pm

    Caching for View pages is kind a confusing though. 🙁

    Reply
  11. Marie Ann Dominic Osorio says

    June 17, 2015 at 12:46 am

    Thank you so much! This helps me a lot. 🙂 Keep writing.

    Reply
  12. 3dpillar.com says

    June 23, 2015 at 4:38 am

    nice article. I have used for one of my website

    thanks

    Reply
  13. Harishchandra says

    October 8, 2015 at 2:27 am

    Need More clarification on caching!. can you brief?

    Reply
  14. kheteshkumawat says

    December 31, 2015 at 2:00 am

    easy to understand ci about cache

    Reply
  15. Jyoti pawar says

    July 19, 2016 at 2:25 pm

    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

    Reply
  16. Collins Ushi says

    February 8, 2017 at 10:27 am

    How can I make Codeigniter CSRF protection work when page caching and captcha are used?

    Reply
  17. Bhumika says

    November 1, 2017 at 2:19 am

    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 ?

    Reply

Leave a Reply Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Primary Sidebar

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Follow Us

  • Twitter
  • Facebook

Top Posts & Pages

  • How To Work With JSON In Node.js / JavaScript
    How To Work With JSON In Node.js / JavaScript
  • PHP HTML5 Video Streaming Tutorial
    PHP HTML5 Video Streaming Tutorial
  • How To Work With C# Serial Port Communication
    How To Work With C# Serial Port Communication
  • LinQ Query With Like Operator
    LinQ Query With Like Operator
  • Facebook C# API Tutorials
    Facebook C# API Tutorials
  • Using Supervisord Web Interface And Plugin
    Using Supervisord Web Interface And Plugin
  • Get Facebook C# Api Access Token
    Get Facebook C# Api Access Token
  • Beginning Codeigniter Application Development
    Beginning Codeigniter Application Development
  • How To Use Hotkeys/Keyboard Events In WPF Application Using C#
    How To Use Hotkeys/Keyboard Events In WPF Application Using C#
  • Control HTML5 Audio With Jquery
    Control HTML5 Audio With Jquery

Recent Posts

  • Building Auth With JWT – Part 2
  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read

Tags

.net angularjs apache api audio auth authenticatin aws c# cloud server codeigniter deployment docker doctrine facebook git github golang htaccess html5 http javascript jwt linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty socket.io tfs tips unit-test utility web application wordpress wpf

Footer

Archives

Follow Us

  • Twitter
  • Facebook

Subscribe to Blog via Email

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 3,774 other subscribers

Copyright © 2023