CodeSamplez.com

Programming, Web development, Cloud Technologies

  • Facebook
  • Google+
  • RSS
  • Twitter
  • 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
Home Development How To Work With Codeigniter Caching In PHP

How To Work With Codeigniter Caching In PHP

Rana Ahsan January 22, 2013 17 Comments


 How To Work With Codeigniter Caching In PHP    

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 for improving our web application to a new level. I am assuming you have some codeigniter basics knowledge already and have experience to write simple codes using Codeigniter standards.

Why Caching?

codeigniter caching
“I am coding and my code is working well, why the hell I need to implement caching techniques?”
Well, this kind of thinking is natural. To understand the main concern behind, we will need to come out from the domain of “only coding the functionality” to a little higher level of thinking. Two most important factors are as follows:

Applications Performance: It’s vital because it’s 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, its gonna be a lot noticeable/annoying to them. Faster web application is always brings peace to a visitor’s mind.

Reduce Server Overhead: The more your web application/site becomes popular, the more your server have to work more. It’s always better to think about lessen the server’s computing/communication load as much as possible. Otherwise, for overloaded or spike traffic, server may crash often. You can have a highly configured server to handle this, but, will cost a lot which you don’t need to at all. As this doesn’t happen always, 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 web sites/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 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. lets dig into them one by one.

CodeIgniter Cache Control Technique For Browser:

By default, web browsers do cache the results which our server generates.Here, we can tell the browser not to cache. Usually, we won’t want to prevent browser from caching except some special cases where our outputs are updated very often. So, instead of setting this commands as global/base controller, lets practice to use it only in the controllers/controller functions where it’s really needed. You can use the following code snippets only when you really 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"); 

CodeIgniter Caching For View Pages:

web cache workflow
OK, so let us move one level more deeper. We now wan 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 not using any, then codeigniter’s internal support is really very helpful. Use the code example as 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....
}

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 the entire controller’s functionality. Check out codeigniter documentaiton on web page caching for more details description.

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 application to new server which doesn’t support any caching?
Well, you might be wondering, what we will do in such cases. Would we change code to disable all cache? No, we won’t need so. 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?

Lets 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; 
}

Whenever the above function is being called, it will return data from its cache up to 2 minutes, and then 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 in libraries, totally depends 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 performance of your application.

Luckily, using this is also as simple as other codeigniter functionality. We just need to provide command to cache result 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();

as soon as we give the instruction to cache ‘on’, it will start caching all the results following it. If you need somewhere to disable caching, just use ‘cache_off’ function before the execution. See complete documentation on database caching for more information.

Hope this brief codeigniter caching tutorial will help you understand and start to improve your web application to be more robust/scalable. Do not hesitate to ask if you have any questions/comments. Happy coding ๐Ÿ™‚

Related

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

About Rana Ahsan

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

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.

Email Subscription

Never miss any programming tutorial again.

Popular Tutorials

  • PHP HTML5 Video Streaming Tutorial
  • How To Work With JSON In Node.js / JavaScript
  • Generate HTTP Requests using c#
  • How To Work With C# Serial Port Communication
  • Facebook C# API Tutorials
  • How To Work With CodeIgniter Pagination
  • Get Facebook C# Api Access Token
  • LinQ To SQL Database Update Operations In C#
  • How To Work With Multithreaded Programming In C#.NET Application
  • Getting Started With HTML5 Web Speech API

Recent Tutorials

  • Building Auth With JWT – Part 1
  • Document Your REST API Like A Pro
  • Understanding Golang Error Handling
  • Web Application Case Studies You Must Read
  • Getting Started With Golang Unit Testing
  • Getting Started With Big Data Analytics Pipeline
  • NodeJS Tips And Tricks For Beginners
  • Apple Push Notification Backend In NodeJS
  • Web Based Universal Language Translator, Voice/Text Messaging App
  • How To Dockerize A Multi-Container App From Scratch

Recent Comments

  • intolap on PHP HTML5 Video Streaming Tutorial
  • manishpanchal on PHP HTML5 Video Streaming Tutorial
  • Rana Ghosh on PHP HTML5 Video Streaming Tutorial
  • ld13 on Pipe Email To PHP And Parse Content
  • Daniel on PHP HTML5 Video Streaming Tutorial

Archives

Resources

  • CodeSamplez.com Demo

Tags

.net apache api audio aws c# cache cloud server codeigniter deployment doctrine facebook git github golang htaccess html5 http image java javascript linq mysql nodejs oop performance php phpmyadmin plugin process python regular expression scalability server smarty ssh tfs thread tips ubuntu unit-test utility web application wordpress wpf

Copyright © 2010 - 2021 · CodeSamplez.com ·

Copyright © 2021 ยท Streamline Pro Theme on Genesis Framework ยท WordPress ยท Log in