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 example you just saw cached the output of PHP statements. It's also possible to cache static HTML content, through creative use of PHP's output buffering functions. Consider the following example, which revises the code on the previous page to cache HTML markup instead of PHP command output:
In this case, PHP's output buffering functions have been used to capture all the output generated subsequent to the call to ob_start(), and store this output in a buffer. Once the entire output has been captured, the ob_get_contents() function is used to retrieve the buffer contents to a variable. This variable (which now contains the entire HTML page) is then stored in the cache for future use. Finally, the ob_end_flush() function is used to end output buffering and send the contents of the buffer to the browser.
{mospagebreak title=Different Strokes}
An alternative method to accomplish the task on the previous page lies with the Cache_Lite_Output() class, a subclass of the Cache_Lite class. This subclass (which internally uses output buffering) inherits all of the attributes of the parent class, and adds two methods to the parent class' method collection: a start() method, which begins caching data, and an end() method, which marks the end of data caching.
Consider the following variant of the example on the previosu page, which illustrates how this may be used:
Over here, if the call to start() - which is provided with a cache identifier - returns true, it implies that the requested data has already been cached, and the Cache_Lite_Output object takes care of printing the contents of the cache. If, however, the call to start() returns false, it implies that the data is not present in the cache, and so all subsequent output generated by the script will be cached, until the object's end() method is invoked.