As Web applications become more and more complex, cleverdevelopers can use application-level caching to improve the performanceof their PHP scripts. This article shows you how, discussing the PEARCache_Lite class with examples that illustrate how it can be used in alive environment.
The Cache_Lite class comes courtesy of PEAR, the PHP Extension and Application Repository (http://pear.php.net). In case you didn't know, PEAR is an online repository of free PHP software, including classes and modules for everything from data archiving to XML parsing. When you install PHP, a whole bunch of PEAR modules get installed as well; the Cache_Lite class is one of them.
In case your PHP distribution didn't include Cache_Lite, you can get yourself a copy from the official PEAR Web site, at http://pear.php.net - simply unzip the distribution archive into your PEAR directory and you're ready to roll!
Let's begin with something simple - building a primitive cache using Cache_Lite object methods. Here's the code:
<?php
// include the package
require_once("Lite.php");
// set an ID for this cache
$id = "starwars";
// set some variables
$options = array(
"cacheDir" => "cache/",
"lifeTime" => 50
);
// create a Cache_Lite object
$objCache = new Cache_Lite($options);
// test if there exists a valid cache
if ($quote = $objCache->get($id))
{
// if so, display it
echo $quote;
// add a message indicating this is cached output
echo " [cached]";
}
else
{
// no cached data
// implies this data has not been requested in last cache lifetime
// so obtain it and display it
$quote = "Do, or do not. There is no try. -- Yoda, Star Wars";
echo $quote;
// also save it in the cache for future use
$objCache->save($quote, $id);
}
?>
Don't worry if it didn't make too much sense - all will be explained shortly. For the moment, just feast your eyes on the output:
Do, or do not. There is no try. -- Yoda, Star Wars
Now refresh the page - you should see something like this, indicating that the second occurrence of the page has been retrieved from the cache.
Do, or do not. There is no try. -- Yoda, Star Wars [cached]
Let's take a closer look at how this was accomplished, on the next page.