Home arrow PHP arrow Page 4 - Caching Result Sets in PHP: The Barebones of a Caching Class

Caching with class: a deeper look at the “Cache” class - PHP

While procedural caching may be well-suited for small and even medium-sized applications, the picture changes for large projects. That's when object-oriented approaches come into their own. This article focuses on developing an object-based extensible caching solution.

TABLE OF CONTENTS:
  1. Caching Result Sets in PHP: The Barebones of a Caching Class
  2. Chaining things along: a quick look at the procedural caching solution
  3. The object-oriented solution: developing a result set caching class
  4. Caching with class: a deeper look at the “Cache” class
  5. More class methods in detail: ending up the round
By: Alejandro Gervasio
Rating: starstarstarstarstar / 7
October 10, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

Certainly, there are many trusted caching classes on the Web, ready to be quickly implemented within an application. Regarding this situation, I’m definitely not trying to market my caching class. Personally, I think that the structure of the class is extensible and points out its functionality to perform a specific task. Very often I’ve seen classes that are packaged with a wealth of methods that don’t maintain a strict relationship with the objective for which these classes were created.

In this case, since the main goal of the class is to cache results sets in a file, its methods are set up specifically to perform related tasks. Any other processes, such as database handling, query execution and error handling, are delegated to other classes. Thus, the reason for implementing object aggregation inside the class should become clear now.

But, I promised a detailed explanation of each method, so let’s start looking at the constructor. The method takes the following parameters: $mysql, which represents a reference to a MySQL object, in order to provide the class with the ability to handle database operations. Then, the second argument, $expiry means the expire time expressed in seconds for the cache to be considered valid, while the third parameter, $cacheFile, simply specifies the name of the cache file where the result set will be stored.

At times, it’s useful to give default values for some parameters, thus I’ve done so for the expire time and the cache file. The constructor assigns the values passed directly to it as data members, like this:

// constructor
function Cache(&$mysql,$expiry=86400,$cacheFile='default_cache.txt'){
            $this->mysql=&$mysql;
            (is_int($expiry)&&$expiry>0)?$this->expiry=$expiry:$this->mysql->isError
('Expire time must be a positive integer');
            $this->cacheFile=$cacheFile;
            $this->data=array();
}

The only thing to notice here is the creation of the $this->data array. This property represents the result set to be returned either by a regular query or obtained directly from the cache file. We’ll see more about it in a few moments.

As for the procedural approach, the “readCache()” and “writeCache()” private methods are the actual class’ workhorses, since they read and write the cache file in accordance with the class logic. The “writeCache()” method looks slightly more complex, as you can see in the listing below:

// write cache file
function write(){
            if(!$fp=fopen($this->cacheFile,'w')){
                        $this->mysql->isError('Error opening cache file');
            }
            if(!flock($fp,LOCK_EX)){
                        $this->mysql->isError('Unable to lock cache file');
            }
            while($row=$this->result->fetchRow()){
                        $content[]=$row;
            }
            if(!fwrite($fp,serialize($content))){
                        $this->mysql->isError('Error writing to cache file');
            }
            flock($fp,LOCK_UN);
            fclose($fp);
            unset($fp,$row);
            return $content;
}

This method opens or tries to create a cache file, then gets a result set that is properly serialized. Finally, it writes the serialized data to the cache file, and returns the results for further processing.

Notice that each potential error condition is handled by the “isError()” method that belongs to the MySQL wrapping class. Errors are handled in this way for keeping the code more readable. However, I strongly recommend that you delegate any possible errors to another object that provides a centralized error handling mechanism. Programmers that have already worked with exceptions in PHP 5 probably know that they provide a useful method for efficiently handling errors by using one single point within an application.

As you can see, file locking is implemented at a basic level, but this method may not work properly for different operating systems. Just make sure that you’re working with a file locking method that is supported by the operating system on which the application will be run.

The only thing left to be reviewed is the way that each table row is retrieved. Please see that the method uses the “fetchRow()” method to fetch rows. However, the method is taken as a “temporary loan,” since it belongs to the $this->result object. Once again, we’re using aggregated objects for performing some tasks that are not strictly related to the “Cache” class itself.

If this sounds rather confusing, the relationship between classes will become clear when we look at the complete source code for each class used in this series. By now, it’s more than enough for explaining the logic of the caching class.

As we’ve seen, the other relevant method is “readCache()”, which reads the cache file, and returns the unserialized data array for being processed. This is best understood by showing its short definition:

// read cache file
function read(){
            if(!$content=unserialize(file_get_contents($this->cacheFile))){
                        $this->mysql->isError('Error reading from cache file');
            }
            return $content;
}

Okay, there are still some methods that need to be properly explained, in order to fully understand how the class works. So, join me in the next section to learn more about their functionality.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: