Caching – Save visitors time and Balance the load

Caching is a major process of speeding up your application. By caching the output of a potentially large scale operation and displaying that output later from that cache saves a lot of time. First if you have cached output of a large scale operation, just check whether the cache is out-of-date or not. If it succeeds all the parameters, display the cache which saves that time consuming procedures. These large scale operation may include fetching content from an remote source using CURL or any stream wrapper, or a database operation, or even a time consuming graph/chart generation.

There are several types of caching, like opcode caching, output caching etc. Compiler level caching are out of scope in this article. We are simply talking about the output caching. In this step PEAR::Cache or PEAR::Cache_Lite may save really a great amount of time. Lets take a look how.

In the following example we are using PEAR::Cache. You can also use Cache_Lite which functions great by sacrificing a bit performance.

<?
include("Cache/Output.php");

$cache = new Cache_Output("file");
if (!$cache->start($cacheid, "samplegroup"))
{
	//perform large scale operation
        echo "Hello";
	$cache->end();
}
else
{
	echo "Printing from Cache";
}

//display the cached content
echo $cache->get($cacheid);
?>

First time, the output is generated as usually. But from next time the output is displayed from cached bypassing the large scale operation.

You can flush content of any cached group by accessing it’s flush() method which looks like below

$cache->flush( “samplegroup”);

Thats it.