PHP
  Home arrow PHP arrow Page 4 - 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 - Caching with class: a deeper look at the “Cache” class
    ( Page 4 of 5 )

    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
     

       

    PHP ARTICLES

    - Using Directory Iterators to Build Loader Ap...
    - Using the spl_autoload() Functions to Build ...
    - Working Out of the Object Context to Build L...
    - Using the _autoload() Magic Function to Buil...
    - The Destruct Magic Function in PHP 5
    - The Autoload Magic Function in PHP 5
    - Developing a Recursive Loading Class for Loa...
    - The Sleep and Wakeup Magic Functions in PHP 5
    - Using the Clone Magic Function in PHP 5
    - Including Files Recursively with Loader Appl...
    - The Call Magic Function in PHP 5
    - Designing a Captcha System with PHP and MySQL
    - Using Static Methods to Build Loader Apps in...
    - The Isset and Unset Magic Functions in PHP 5
    - Advanced PHP Form Input Validation to Check ...





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