HomePHP Page 2 - Building a Template Parser Class with PHP, Part II
One step forward: defining caching methods - PHP
In part one of this two part article series, you learned how to build a simple template parser class in PHP. In this second article, you will learn how to add caching capabilities to the class.
The first question that came to my mind when I decided to implement a caching mechanism was: is it really worth having those capabilities? The answer was a resounding yes! Let’s think about it. If we’re working with websites that don’t change their content very often, say on a daily basis, it’s highly desirable to have a caching system that simply reads the contents to be displayed from a flat file, and delivers them directly to the browser, without the need to process a template file each time the requested page has to be rendered. That sounds like common sense..
With this conclusion firmly in mind, I quickly started implementing those desirable caching capabilities inside the class. To keep things ordered, I defined two class methods for reading and retrieving data from a specific cache file, specifying a time-based cache validity policy. The first caching method, "readCache()" simply reads data from a cache file, and is defined in the following way:
As you can appreciate, the above method takes two parameters: the cache file and time expiry, respectively, allowing us to specify a value expressed in seconds for setting the proper cache validness.
The method checks simultaneously if there is a cache file in the system and that the time expiry has not been reached. Accordingly, if the cache file exists and is valid, the contents from the file are returned. Otherwise, the method returns false. Certainly, you’ll agree with me that this is not rocket science.
Now, let’s take a look at the next method, "writeCache()", which, not surprisingly writes contents to a specified cache file:
function writeCache($cacheFile,$content){
$fp=fopen($cacheFile,'w');
fwrite($fp,$content);
fclose($fp);
}
On the opposite side, this method accepts a cache file name, and the contents to be written on it as parameters. It naturally opens the file, writes the contents (overriding any previous values) and closes the file. The method is straightforward and easy to understand.
At this point, we’re armed with two methods to read and write cache files in an efficient manner. It’s time place them into the class puzzle.