PHP
  Home arrow PHP arrow Page 4 - 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 - 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


       · 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