PHP
  Home arrow PHP arrow Page 2 - Caching Result Sets in PHP: Object Int...
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: Object Interaction Within a Caching System
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 4
    2005-10-17

    Table of Contents:
  • Caching Result Sets in PHP: Object Interaction Within a Caching System
  • The first link in the caching process: looking at the “Cache” class
  • The second link in the caching process: overview of the “MySQL” class
  • The third link in the caching process: a quick look at the “Result” class
  • Chaining the links: putting the classes together

  • 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: Object Interaction Within a Caching System - The first link in the caching process: looking at the “Cache” class


    (Page 2 of 5 )

    In order to get a better understanding of the interaction process between classes, let’s remind ourselves of how the “Cache” class looks, since it’s the first relevant structure within the caching system. To refresh our memories, here is the complete definition for this class:

    class Cache{
                var $mysql;  // instance of MySQL object
                var $result; // instance of Result object
                var $expiry; // cache expire time in seconds
                var $cacheFile; // cache file
                var $data; // result set array
                // 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();
                }
                // 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()){
                                       $this->result=$this->mysql-
    >query($query);
                                       $this->data=$this->write();
                            }
                            else {
                                       $this->data=$this->read();
                            }
                }
                // 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;
                }
                // read cache file
                function read(){
                            if(!$content=unserialize
    (file_get_contents($this->cacheFile))){
                                       $this->mysql->isError('Error
    reading from cache file');
                            }
                            return $content;
                }
                // 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;
                }
                // 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;
                }
    }

    So far, so good. Since the class has been explained in detail over the third part of the series, I won’t stop long on it. Let’s take a brief look at some of its most important features, before jumping directly into the source code for the other classes.

    As we’ve seen before, the “Cache” class allows you to store an entire result set in a cache file for a given time period. Once the expiry has been reached, a new query is run for getting “fresh” data, and then the cache generation is carried out again. As long as the cached data is valid, it will be read from the file, being available for some kind of further processing.

    Asides from the regular methods to handle programmatically the cached data, the class exposes some additional methods for fetching either single rows or multiple rows, as well as the ability to count rows.

    Indeed, these features don’t present any difficulties. However, there are some interesting things within the class definition. Note that database connectivity tasks, query execution, and error handling are delegated to different classes. This implicitly means that there must be other objects that are passed to the “Cache” class for carrying out these specific operations.

    Essentially, we can see that all of the database work is done by a MySQL object, which is passed to the class by its constructor. Therefore, it’s time to take a look at the MySQL abstraction class, responsible for connecting to MySQL, selecting databases and running queries.

    More PHP Articles
    More By Alejandro Gervasio


       · In this fourth part of the series, the result-set caching class is integrated with...
       · Great set of articles, it's exactly what I was looking for.I am having some...
       · Hello,Thanks for commenting on the article. Regarding your question, the reason...
       · I'm just wondering why not using PEAR :: DB instead of creating new classes for...
       · Thanks for the comments on my article and my classes.In fact, I'm not reinventing...
       · Thank you for answering back.I do see your point, but let me add this. It's true...
       · Thank you for your reply.I understand your point too. What you said about PEAR...
       · I have coded in several different languages prior to using PHP, and have more of a ...
       · I'm glad to know that this series have been quite helpul for you in learning the OOP...
     

       

    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 5 hosted by Hostway
    Stay green...Green IT