In order to implement a functional result set caching system, we need to make some changes to the original version of the script, so we can take advantage of the data stored in the cache file, directly reading the result set from that file. Also, it's important to clarify that the script will use a time triggered caching approach, thus forcing a new cache generation each time an expiry timestamp is reached. Therefore, having defined the overall features of the caching system, the brand new version of the script looks like this: function writeCache($data,$cacheFile='default_cache.txt') } Okay, let's break down the code to analyze in detail the tasks accomplished by each section. First, we've defined some wrapping functions that take care of reading and writing data to the cache file, along with other simple functions that connect to MySQL, select a database and execute a query. But let's take a look at the "writeCache()" function. As you can see, it accepts two parameters: the data to be written to the cache file, and the name of the cache file being used. This function simply writes serialized data to the given cache file, so in this case the serialized data will be the array obtained from a result set. The referenced function is listed below: function writeCache($data,$cacheFile='default_cache.txt'){ Notice that I'm using a generic file locking method when writing data to the cache file. However, this might not work properly on some network operating systems. So, be aware of this, in order to implement a file locking method that works in the operating system of your choice. Now, let's have a look at the "readCache()" function, which reads from the cache file, by reversing the serialized data, and restoring it to its original state: function readCache($cacheFile){ The only thing to note here is how the data is returned by the function, as stated previously, by using the "unserialize()" function, which is listed below: return unserialize(file_get_contents($cacheFile)); By now, we've defined the most relevant functions for implementing the result set caching system. As you might guess, the rest of the functions are fairly self-explanatory. They connect to MySQL, then select a database and finally perform a given query. Here's the list of each one of them, beginning with the "connectMySQL()" function: function connectMySQL($host,$user,$password,$database){ Lastly, the "query()" function: function query($query){ I'm sure that you've used similar functions hundreds of times, so I won't spend time on them. Instead, I'll focus primarily on the logic of the caching script. Thus, join me in the next explanation to see how this caching system can be put quickly into action. Let's go!
blog comments powered by Disqus |