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.
Here's another, more realistic example, which caches a database result set and uses the cached set in order to reduce the time spent on executing subsequent queries for the same data. The result set is obtained via a function called get_headlines(), converted into a PHP array and cached using the call() method of the Cache_Lite_Function class.
<?php
// returns an array of headlines from a database
function get_headlines()
{
// open connection to database
$connection = mysql_connect("localhost", "joe", "secret")
or die ("Unable to connect!");
mysql_select_db("db111") or die ("Unable to select database!");
// formulate and execute query
$query = "SELECT headline FROM news ORDER BY timestamp DESC";
$result = mysql_query($query) or die("Error in query: " . mysql_error());
// iterate over result set and create array
while ($row = mysql_fetch_object($result))
{
$arr[] = $row->headline;
}
// close connection
mysql_close($connection);
// return array of records
return $arr;
}
// include the class
require_once('Function.php');
// configure the cache
$options = array(
'cacheDir' => 'cache/',
'lifeTime' => 600
);
// create an instance of the Cache_Lite_Function object $objCache = new Cache_Lite_Function($options);
// cache the call to the get_headlines() function
// if return value is present in cache,
// Cache_Lite_Function will fetch it from the cache
// else the function will be called and the result returned $data = $objCache->call('get_headlines');