PHP
  Home arrow PHP arrow Page 5 - Caching Result Sets in PHP: The Barebones of a Caching Class
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Caching Result Sets in PHP: The Barebones of a Caching Class
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 7
    2005-10-10


    Table of Contents:
  • Caching Result Sets in PHP: The Barebones of a Caching Class
  • Chaining things along: a quick look at the procedural caching solution
  • The object-oriented solution: developing a result set caching class
  • Caching with class: a deeper look at the “Cache” class
  • More class methods in detail: ending up the round

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Caching Result Sets in PHP: The Barebones of a Caching Class - More class methods in detail: ending up the round
    ( Page 5 of 5 )

    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
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 2 Hosted by Hostway
    Stay green...Green IT