PHP
  Home arrow PHP arrow Page 5 - Caching Result Sets in PHP: The Barebo...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Mobile Linux 
App Generation ROI 
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: 4 stars4 stars4 stars4 stars4 stars / 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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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!


    DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.

       · This part of the series goes through the makings of the basic structure for a...
       · Am I the only one who only sees part 1 and 3?
       · Hello,Thank you for commenting on the article. And regarding your question,...
       · The second part was scheduled for today, but an editing mix-up placed the third...
       · The second part of the article was published today. Here is the link...
       · Thank you very much for your easy to understand articles. I am using much code...
       · Another solution for my case would involve creating a db table named...
       · Hello,Thanks for commenting on the article. It's always nice to get your...
       · Hello again,Regarding your caching alternative, try to keep your database access...
       · Thank you for your input. It gives me a better understanding of the usage for this...
       · Hello,Thank you for the compliments on the series I wrote, and I'm glad to hear...
     

       

    PHP ARTICLES

    - Authentication Scripts for a User Management...
    - Utilizing the Use Keyword for Namespaces in ...
    - Building a User Management Application
    - Working With Different Namespaces in PHP 5
    - User Management Explained: Overview
    - Using Namespaces in PHP 5
    - Database Security: Guarding Against SQL Inje...
    - Building a Modular Exception Class in PHP 5
    - Database and Password Security for Web Appli...
    - Handling MySQL Data Set Failures in PHP 5
    - Building Site Registration for Web Applicati...
    - Intercepting Customized Exceptions in PHP 5
    - Securing Your Web Application Against Attacks
    - Sub Classing Exceptions in PHP 5
    - Authentication for Web Application Security





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway
    Stay green...Green IT