Loading PHP 5 classes using a traditional approach: developing an illustrative example An adequate place to start demonstrating how the “__autoload()” PHP 5 magic function works is by developing a simple database-driven application, where all of the classes required by the application in question are loaded into client code by using a couple of “require_once()” functions. By creating this “conventional” sample application, you’ll have at your disposal an excellent point of reference for comparing the pros and cons of using this approach with utilizing one that implements the mentioned “__autoload()” function. Having clarified this point, suppose that there’s a MySQL database table that has been populated with some basic data about a few fictional users, which needs to be displayed on the browser. To perform this process as easily as possible, I’ll use two different MySQL handling classes that will reside in different files. In this case, the first class, called “MySQL,” was previously stored on a “mysql.php” file. It has the following signature: class MySQL{ private $host; private $user; private $password; private $database; private $connId; // constructor function __construct($options=array()){ if(!is_array($options)){ throw new Exception('Connection options must be an array'); } foreach($options as $option=>$value){ if(empty($option)){ throw new Exception('Connection parameter cannot be empty'); } $this->{$option}=$value; } $this->connectDb(); } // private 'connectDb()' method private function connectDb(){ if(!$this->connId=mysql_connect($this->host,$this->user,$this->password)){ throw new Exception('Error connecting to MySQL'); } if(!mysql_select_db($this->database,$this->connId)){ throw new Exception('Error selecting database'); } } // public 'query()' method public function query($sql){ if(!$result=mysql_query($sql)){ throw new Exception('Error running query '.$sql.' '.mysql_error()); } return new Result($this,$result); } } You might find the definition of the above “MySQL” class quite familiar, since I used it in some of my previous articles on PHP development. As you can see, this class defines a group of methods for connecting to the pertinent database server, as well as for performing queries against one or more tables. So far, the signature of this class is not rocket science at all.
blog comments powered by Disqus |
|
|
|
|
|
|
|