HomePHP Page 4 - Caching Result Sets in PHP: Porting the Code to PHP 5
Yet another modified class: updating the “Result” class - PHP
In this part of the series, you will see in detail an updated version of each class that composes the caching system, for a correct implementation in PHP 5. Also, the “Cache” class will be modified to work with an array processor class that handles array operations. It should help refresh your memory of techniques related to object-oriented programming.
As you may probably guess, the process for updating the “Result” class is pretty straightforward. Applying the same modifications introduced to the MySQL class, we end up defining the code for this class as follows:
class Result { private $mysql; // instance of MySQL object private $result; // result set // constructor public function __construct(&$mysql,$result){ $this->mysql=&$mysql; $this->result=$result; } // fetch row public function fetchRow(){ return mysql_fetch_array($this- >result,MYSQL_ASSOC); } // count rows public function countRows(){ if(!$rows=mysql_num_rows($this->result)){ throw new Exception('Error counting rows'); } return $rows; } // count affected rows public function countAffectedRows(){ if(!$rows=mysql_affected_rows($this- >mysql->conId)){ throw new Exception('Error counting affected rows'); } return $rows; } // get ID from last inserted row public function getInsertID(){ if(!$id=mysql_insert_id($this->mysql- >conId)){ throw new Exception('Error getting ID'); } return $id; } // seek row public function seekRow($row=0){ if(!mysql_data_seek($this->result,$row)){ throw new Exception('Error seeking data'); } } }
Once again, I’ve explicitly defined the class’ member visibility, as well as delegated runtime error conditions by throwing exceptions within conflicting sections of the code. That way, either when fetching result rows or moving the result set’s internal pointer, potential errors are easily handled by an exception mechanism.
With the two above classes already updated to PHP 5, it’s time to look at the workhorse of the whole caching system: the “Cache” class. Let’s jump to the next section to find out how this class is properly updated.