» Speedup your website with Cache_Lite

Every time a request hits your server, PHP has to do a lot of processing, all of your code has to be compiled & executed for every single visit. Even though the outcome of all this processing is often identical for both visitor 21600 and 21601. So why not save the flat HTML generated for visitor 21600, and serve that to 21601 as well? This will relieve resources of your web server and database server because less PHP often means less queries.

Cache_Lite

Now you could write such a performance system yourself but there's a neat package in PEAR called Cache_Lite that can do this for us, benefits:

  • it saves us the time of inventing the wheel
  • it's been thoroughly tested
  • it's easy to implement
  • it's got some cool features like lifetime, read/write control, etc.

Now you don't need to cache entire pages, you can also just cache parts of pages if that's easier to implement.

Install Cache_Lite

Installing is like taking candy from a baby. On Ubuntu I would use aptitude like this:

sudo aptitude -y update
sudo aptitude install php-pear

And now that we have PEAR, i would use it to install the Cache_Lite extension:

sudo pear install Cache_Lite

And we're ready!

Implement Cache_Lite

So let's see how we can implement Cache_Lite into our scripts. The basic idea is that we have a unique identifier for every page. You can make it up, get it from your database, or use the REQUEST_URI. Cache_Lite will see if it stored content for that identifier before, and if it's fresh enough. If so, it will retrieve the stored HTML from disk and echo it right away. If not, we: 

  • turn on output buffereing so we can catch all following content
  • we include the original PHP code
  • catch the output buffer, and let Cache_Lite store it on disk for the next time.
  • and then echo it

This is a PHP example:

/* Include the class */
require_once 'Cache/Lite.php';
 
/* Set a key for this cache item */
$id = 'newsitem1';
 
/* Set a few options */
$options = array(
    'cacheDir' => '/var/www/www.mywebsite.com/cache/',
    'lifeTime' => 3600
);
 
/* Create a Cache_Lite object */
$Cache_Lite = new Cache_Lite($options);
 
/* Test if there is a valid cache-entry for this key */
if ($data = $Cache_Lite->get($id)) {
    /* Cache hit! We've got the cached content stored in $data! */
} else {
    /* Cache miss! Use ob_start to catch all the output that comes next*/
    ob_start();
 
    /* The original content, which is now saved in the output buffer */
    include "realcontent.php";
       
    /* We've got fresh content stored in $data! */
    $data = ob_get_contents();
       
    /* Let's store our fresh content, so next
     * time we won't have to generate it! */
    $Cache_Lite->save($data, $id);
    ob_get_clean();
}
echo $data;

In this example, the real, original php code is stored in realcontent.php

Let Cache Live in RAM

If your want, you can have all the static html files served from the server's internal memory. Now this would really speedup things. Checkout my other article Create turbocharged storage using tmpfs to learn how.

More Cache_Lite

One thing I always like to do, is to automatically purge an article's cache when a comment has been placed. You could for example place this before Cache_Lite checks if it's got a cache page for a specific $id:

if(isset($_POST["add_comment"]) && $_POST["add_comment"]){
    $Cache_Lite->remove($id);
}

Take some time to read the comments in the source code, it's actually pretty easy.


Like this article?

   Then Dzone it!
Or use another bookmark button below to show your support &
help me spread the word.


tags: performance, caching, PEAR, php
category: Programming - PHP
read: 20,280 times

Add comment

(required, shown)(required, not shown)for syntax highlighting

[CODE="Javascript"]
your_code_here();
[/CODE]

Replace "Javascript"
with "php", "text", etc.
code (to make sure you are not a spammer)

Comments

#22. Dilli R. Maharjan on 18 June 2008

Default avatar:Dilli R. MaharjanThanks Kevin, I was busy on other stuff. Thanks again for the suggestions.

#21. Proea on 16 June 2008

Default avatar:ProeaThanks

#20. Kevin (link) on 31 May 2008

Member avatar: Kevin@ Dilli R. Maharjan: You could do that yes, but Cache_Lite also provides methods to delete specific cached keys. You should review the (tiny) manual.

#19. Dilli R. Maharjan on 27 May 2008

Default avatar:Dilli R. MaharjanGreat article, It helped me a lot.
I searched for infromation regarding cache hit, cache miss and regarding cache stat and I did not find any. Someone please refer any URL regarding them. I am confused regarding how to flush my cache, simplying deleted cached directory work or not? Please help.

#18. Kevin (link) on 04 March 2008

Member avatar: Kevin@ wireholic: maybe i'll write another article some day that diggs a little deeper. thanks for your remark and you're right, I'll update the article

#17. wireholic on 04 March 2008

Default avatar:wireholicHey.

Good introduction to Cache_Lite.

However if you want to cache bigger sites than blogs,little portals etc. You should look deeper into Cache_Lite functionalities its really powerfull. Thereis a good article on the Sitepoint's page.
... [more]
One more thing, if you dont want your data to duplicate at the first time the page is loaded add ob_end_clean() just after "$Cache_Lite->save($data, $id);" line to clear output buffering data. That should be noticed.

Cheers.

#16. Kevin (link) on 23 November 2007

Member avatar: Kevin@ Ashish: I've never used Smarty, but you should at least be able to implement it for caching entire pages. I would say play around with it a bit and see how flexibile Smarty really is.

#15. Ashish on 23 November 2007

Default avatar:AshishHi,

Thanks for this, do you have any idea on using this with Smarty?

Any tips?

#14. seonet on 31 October 2007

Default avatar:seonetThanks Kevin
:D

#13. Kevin (link) on 29 October 2007

Member avatar: Kevin@ seonet: Hi, for example. If I wanted to cache this entire article, a logical $id would be: 'speedup_your_website_with_cache_lite' or maybe the internal article id like: 189 or something. If I only wanted to cache the comments section a logical id would be: 'speedup_your_website_with_cache_lite.comments'

See? You're totally free in what id to pick, just as long as it's unique and logically for you

#12. seonet on 29 October 2007

Default avatar:seonetHi Kevin,
I want to ask about how to assign $id
one $id for one cache file or what ?
So if I create template files in cache ->
I need assign one file with unique $id or how ?
... [more] I read in somewhere "
$id = md5($strSQL);
if($cache->get($id)){
//
$result = $cache->get($id);
} else {
$result = getAll($strSQL)
$cache->save($result, $id);
}

Hmm, what do you think about code ?

#11. Kevin (link) on 18 October 2007

Member avatar: Kevin@ Moritz: I think you are not providing Cache_Lite with an $options array.

$Cache_Lite = new Cache_Lite($options);

You have to define some options in the options array just like in the example.

#10. Moritz on 18 October 2007

Default avatar:Moritz@Kevin
thanks for your help, but i guess i'm too stupid.
Now i get this error message:
Warning: Invalid argument supplied for foreach() in /....www/PEAR/Cache/Lite.php on line 282

#9. Kevin (link) on 14 October 2007

Member avatar: Kevin@ Moritz: You've installed PEAR in /customers/zweiteherren.com/zweiteherren.com/httpd.www/PEAR and which is not in the include_path. PEAR should be in PHP's include_path so Cache_Lite can find all it's dependencies.

#8. Moritz on 13 October 2007

Default avatar:Moritz@Kevin

Thanks,

it works so far, but i still get this error message at the end of the page:
... [more]
Warning: Cache_Lite::include_once(PEAR.php) [function.Cache-Lite-include-once]: failed to open stream: No such file or directory in /customers/zweiteherren.com/zweiteherren.com/httpd.www/PEAR/Cache/Lite.php on line 536

Warning: Cache_Lite::include_once() [function.include]: Failed opening 'PEAR.php' for inclusion (include_path='.:') in /customers/zweiteherren.com/zweiteherren.com/httpd.www/PEAR/Cache/Lite.php on line 536

Fatal error: Class 'PEAR' not found in /customers/zweiteherren.com/zweiteherren.com/httpd.www/PEAR/Cache/Lite.php on line 537

What's wrong with it?

#7. Kevin (link) on 12 October 2007

Member avatar: Kevin@ Moritz: You're free to cache any page or part of a page you want. You could create a new index.php and rename your old one to real_content.php, you could also do this for a part of your page which isn't very dynamic but does require some heavy php & db operations. So in that case you keep your old index.php but you use the example code to only cache (for example) your sidebar. The original sidebar code goes moves to it's own: sidebar.php, and then that's the file you include instead of real_content.php

#6. Moritz on 11 October 2007

Default avatar:MoritzI really don't understand caching.

in which file di I include realcontent.php?

it's all explained half.

#5. Kevin (link) on 02 October 2007

Member avatar: Kevin@ svetzal: You kan define the keys so that's up to the programmer I think. You can also have Cache_Lite use different directories.

@ Kon: Cache_Lite support some mechanisms to ensure a file has been successfully written to the filesystem. You will have to decide whether or not to use those based on the situation, because of course, every check that's implemented costs performance.

#4. K on 08 September 2007

Default avatar:KWhat happens if two users view the same uncached page at the same time? Do you risk two PHP processes writing to the same file at the same time?

#3. svetzal on 06 September 2007

Default avatar:svetzalBe careful of Cache_Lite - if you have a large number of cache objects, you may get corrupted results back (I have assumed it's duplicate keys). Moved to memcached instead.

#2. Kevin (link) on 06 August 2007

Member avatar: KevinIt means if a cached page is older than 3600 secs (1 hour), it should be removed. This way you automatically get fresh content every hour.

#1. Preeti on 06 August 2007

Default avatar:PreetiWhat does the 'lifeTime' => 3600 in $options array do?