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

More class methods in detail: ending up the round - 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

The next method to be reviewed is the “query()” method. While its definition is extremely simple, its relevance within the class is considerable. Notice that this method accepts a SELECT statement as a parameter, and directly determines when the result set will be updated, thereby forcing a new cache file generation.

If the cache file is found not to be valid, then the query is run, the data is returned from the database and written to the cache file. Otherwise, the data is returned from the cache. These operations are best described looking at the method’s definition:

// if cache is valid, perform query and return a result set. Otherwise, get results from cache file
function query($query){
            // check if query starts with SELECT
            if(!preg_match("/^SELECT/",$query)){
                        $this->mysql->isError('Invalid query. Must start with SELECT');
            }
            if(!$this->isValid()){
                        // read data from MySQL
                        $this->result=$this->mysql->query($query);
                        // write data to cache file
                        $this->data=$this->write();
            }
            else {
                        // read data from cache file
                        $this->data=$this->read();
            }
}

As you can see, the cache update triggering process is internally handled by the “isValid()” private method, because it checks whether the data will be obtained from MySQL or directly from the cache file, as shown in the following lines:

// determine cache validity based on a time expiry trigger
function isValid(){
            if(file_exists($this->cacheFile)&&filemtime($this->cacheFile)>(time()-$this-
>expiry)){
                        return true;
            }
            return false;
}

Here we have an interesting topic that needs to be properly highlighted. Note that the above method is encapsulating the logic for resolving how to trigger the caching system. In this specific case, we’re using a time expiry based caching trigger. However, we’re able to refactor this method in order to handle a different caching strategy. This single feature implies a greater level of flexibility, since several caching triggers might be used either as one single method or as a combination of them.

Finally, the rest of the class methods speak for themselves. The “fetchRow()” method fetches a row from the cached data, handy for returning a row at a time, while the “fetchAll()” method returns all of the cache rows. If we need to count the total number of cache rows, the “countRows()” method easily accomplishes this task.

The code for all of the above explained methods is listed below:

// fetch cache row
function fetchRow(){
            if(!$row=current($this->data)){
                        return false;
            }
            next($this->data);
            return $row;
}
// fetch all cache rows
function fetchAll(){
            if(count($this->data)<1){
                        $this->mysql->isError('Error accessing cache data');
            }
            return $this->data;
}
// count cache rows
function countRows(){
            if(!$rows=count($this->data)){
                        $this->mysql->isError('Error counting cache rows');
            }
            return $rows;
}

Of course, there are some additional methods that might be added to the class for improving its functionality. As usual, feel free to play with the code and write your own methods.

By this point, our round up explaining all of the class methods has hopefully ended. So, let’s proceed to read the corresponding conclusions.

Summarizing

In this third part of the series, I’ve developed an expandable result set caching class that exposes different methods useful for programmatically manipulating cached data. Aside from exploring its structure in detail, I’ve demonstrated how different classes are aggregated to implement an efficient caching mechanism.

However, the big picture is still incomplete. We need to have a look at the rest of the classes that interact within the overall application. Thus, the next article will fully cover that part, in order to put all of the pieces together. Meanwhile, play with the code and add your own features to the caching class. See you in the next part!



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