kvz.io
Published on

Speedup Your Website With Cache_Lite

Authors
  • avatar
    Name
    Kevin van Zonneveld
    Twitter
    @kvz

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 buffering 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:

<?php
/* 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:

<?php
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.

Legacy Comments (26)

These comments were imported from the previous blog system (Disqus).

Preeti
Preeti·

What does the \'lifeTime\' => 3600 in $options array do?

Kevin
Kevin·

It 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.

svetzal
svetzal·

Be 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.

K
K·

What 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?

Kevin
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.

Moritz
Moritz·

I really don\'t understand caching.

in which file di I include realcontent.php?

it\'s all explained half.

Kevin
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

Moritz
Moritz·

@Kevin

Thanks,

it works so far, but i still get this error message at the end of the page:

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/zweiteherr... on line 536

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

Fatal error: Class \'PEAR\' not found in /customers/zweiteherren.com/zweiteherr... on line 537

What\'s wrong with it?

Kevin
Kevin·

@ Moritz: You\'ve installed PEAR in /customers/zweiteherren.com/zweiteherr... 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.

Moritz
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

Kevin
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.

seonet
seonet·

Hi 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 ?
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 ?

Kevin
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

seonet
seonet·

Thanks Kevin
:D

Ashish
Ashish·

Hi,

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

Any tips?

Kevin
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.

wireholic
wireholic·

Hey.

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.

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.

Kevin
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

Dilli R. Maharjan
Dilli R. Maharjan·

Great 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.

Kevin
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.

Proea
Proea·

Thanks

Dilli R. Maharjan
Dilli R. Maharjan·

Thanks Kevin, I was busy on other stuff. Thanks again for the suggestions.

Victor
Victor·

The code works but I can\'t get it to work fine with a php file that contains a msqyl query and is included in a parent file (e.g. template page). That template page contains about 4 cached block and all work fine, except this one that has mysql queries. The cache for that file rewrites with every refresh and I don\'t know why. If I remove the query it works just fine.

Victor
Victor·

I think I got it. I was using the var $id for all block but for this one it didn\'t work. After I renamed it to some other name (say $ident) it worked.

steve shier
steve shier·

Kevin:

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

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

ViserExcizer
ViserExcizer·

Hello, how do I install cache lite manually? If i am on a shared server?