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:
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.