HomePHP Page 3 - Caching Result Sets in PHP: Porting the Code to PHP 5
Taking advantage of an improved object model: updating the caching system to PHP 5 - 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.
In order to use the features of the new object model present in PHP 5, our first step will consist of updating the MySQL abstraction class. Even when the code is closely similar to the previous version, there are several differences that will be easily clarified by looking at the source code. So, the updated MySQL class looks like this:
class MySQL{ private $conId; // connection identifier private $host; // MySQL host private $user; // MySQL username private $password; // MySQL password private $database; // MySQL database // constructor public function __construct($options=array()){ // validate incoming parameters if(count($options)>0){ foreach($options as $parameter=>$value){ if(empty($value)){ throw new Exception('Invalid parameter '.$parameter); } $this-> {$parameter}=$value; } // connect to MySQL $this->connectDB(); } else { throw new Exception('No connection parameters were provided'); } } // connect to MySQL server and select database private function connectDB(){ if(!$this->conId=mysql_connect($this- >host,$this->user,$this->password)){ throw new Exception('Error connecting to the server'); } if(!mysql_select_db($this- >database,$this->conId)){ throw new Exception('Error selecting database'); } } // perform query public function query($query){ if(!$this->result=mysql_query ($query,$this->conId)){ throw new Exception('Error performing query '.$query); } // return new Result object return new Result($this,$this->result); } }
Without a doubt, this class closely resembles the version suitable for PHP 4. However, as you can clearly see, each class member has been defined specifying its visibility. In this case, the only method defined as private is “connectDB()”. The rest of the class methods are publicly accessible from the outside.
The other change introduced to the class is the use of exceptions, within each section of the code where a potential error might occur. See how a new exception is thrown when connecting to the server, selecting a database or running a query? I don't mean that you must be this paranoid regarding error handling, but it doesn’t hurt at all. Trust me.
So far, this MySQL abstraction class doesn’t present big problems to being understood, so let’s move on and put our efforts into updating the “Result” class.