When implementing a cache for your Web page, the first step is, obviously, to include the Cache_Lite class
You can either provide an absolute path to this file, or do what most lazy programmers do - include the path to your PEAR installation in PHP's "include_path" variable, so that you can access any of the PEAR classes without needing to type in long, convoluted file paths. The Cache_Lite object can support multiple caches simultaneously, so long as every cache created has a unique identifier. In this case, I've used the identifier "starwars" to uniquely distinguish the cache I'll be using.
Next, an object of the Cache_Lite class needs to be initialized, and assigned to a PHP variable.
This variable, $objCache, now serves as the control point for cache manipulation. The constructor of the Cache_Lite class can be provided with an associative array containing configuration parameters; these parameters allow you to customize the behaviour of the cache. In the example above, this array contains two parameters, "cacheDir", which specifies the directory used by the cache, and "lifeTime", which specifies the period for which data should be cached, in seconds.
Note that the directory specified must already exist, or else the cache will simply not work. Once an instance of the Cache_Lite object has been created, the business logic to use it becomes fairly simple. The first step is to check if the required data already exists in the cache. If it doesn't, it should be generated from the original data source, and a copy saved to the cache for future use. If it does, you can do something useful with it - write it to a file, pipe it to an external program or - as I've done here - simply output it to the screen for all to admire.
Most of this logic is accomplished via the get() and save() methods of the Cache_Lite object. The get() method checks to see if the data exists in the cache and returns it if so, while the save() method saves data to the cache. The save() method accepts the data to be saved, together with a unique identifier, as input arguments; the get() method uses this identifier to find and retrieve the cached data. The steps above make up a fairly standard process for using the Cache_Lite class, and you'll see them being repeated over and over again in subsequent examples as well.
blog comments powered by Disqus |