» 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.
Stay up to date
You can track my blog
articles and
comments. You may also find my
bookmarks interesting. Or
Follow me on Twitter
Like this article?
|
Then Dzone it! Or use another bookmark button below to show your support & help me spread the word. |
RelatedArticles like this one» Survive heavy traffic with your webserver |
tags: performance, caching, PEAR, php
category: Programming - PHP
read: 34,324 times







tagcloud
#26. ViserExcizer on 14 January 2010
#25. steve shier on 06 May 2009
Your article is good and clear. My cache file is being written but my cache is never hit, apparently because the filename changes. I am just trying to cache a string although later it will be an array of objects populated from a database. Everytime I try to retrieve it , instead of getting the cached data (which I can view in the cached file), it creates a new cache entry. Also, the cache filename seems to change each time. Is therre a way to fix it so it doesn't change and pulls from the cache?
Here's the code
... [more]
In my main file which the user views (Contact.php) I have :
$quote=new QuoteBL();
$quotevalue=$quote->GetNextQuote();
echo "cache=".$quotevalue;
in QuoteBL I have:
class QuoteBL {
//constructor
public function QuoteBL(){
}
public function GetNextQuote(){
//tries to get quote from cache and if no cached data, retrieves data and saves to cache
$data=null;
$cacheid = 'quotearray';
$cache_options = array(
'cacheDir' =>'Cache/data/', //this is the temp directory of the cache files
'lifeTime' =>3600, //time, in seconds, of how long the cache will be valid
'fileNameProtection' => true, //make sure filename is valid
'writeControl' => 'true',
'readControl' => 'true',
'readControlType' => 'md5'
);
$cache=new Cache_Lite($cache_options);
if ($data = $cache->get($cacheid)) {
// data is in our cache, access it through $data
echo "got data from cache<BR>";
}
else { // Not found in cache, it needs to be added
$data="The quality of mercy is not strained";
$cache->save($data,$cacheid,null);
echo "cache empty, save new data in cache<BR>";
}
return $data;
}
}
TIA,
Steve Shier
#24. Victor on 25 February 2009
#23. Victor on 25 February 2009
#22. Dilli R. Maharjan on 18 June 2008
#21. Proea on 16 June 2008
#20. Kevin on 31 May 2008
#19. Dilli R. Maharjan on 27 May 2008
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 on 04 March 2008
#17. wireholic on 04 March 2008
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 on 23 November 2007
#15. Ashish on 23 November 2007
Thanks for this, do you have any idea on using this with Smarty?
Any tips?
#14. seonet on 31 October 2007
:D
#13. Kevin on 29 October 2007
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
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 on 18 October 2007
$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
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 on 14 October 2007
#8. Moritz on 13 October 2007
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 on 12 October 2007
#6. Moritz on 11 October 2007
in which file di I include realcontent.php?
it's all explained half.
#5. Kevin on 02 October 2007
@ 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
#3. svetzal on 06 September 2007
#2. Kevin on 06 August 2007
#1. Preeti on 06 August 2007