HomePHP Page 3 - Building Object-Oriented Database Interfaces in PHP: Working with Multiple Data Access Objects
Code generator in a nutshell: one class that generates another one - PHP
In previous articles in this series, we examined the concept of database interfaces, and saw source code for a "DBIGenerator" class. Working with multiple DB interfaces permits the accomplishment of several operations on many tables at the same time. Alejandro Gervasio demonstrates the power of this concept, with examples.
Once we've called the "generate()" method, one data access object $user has been programmatically created. But let's go one step further: if the object is available to be used, there must be a class from which the object was properly instantiated. That's the main task of this generator class, as you might guess. One DB Interface class has been generated "behind the scenes," providing a bridge between the database table and the application logic. As you've seen before, this is the class that I obtain as a result, after executing the above code:
class User{ var $id=''; var $firstname=''; var $lastname=''; var $email=''; function User(){} function setid($id){ $this->id=$id; } function getid(){ return $this->id; } function setfirstname($firstname){ $this->firstname=$firstname; } function getfirstname(){ return $this->firstname; } function setlastname($lastname){ $this->lastname=$lastname; } function getlastname(){ return $this->lastname; } function setemail($email){ $this->email=$email; } function getemail(){ return $this->email; } function load(){ $r=mysql_query("SELECT * FROM users WHERE id='$this->id'"); return mysql_fetch_array($r,MYSQL_ASSOC); } function submit(){ mysql_query("INSERT INTO users SET firstname='$this- >firstname',lastname='$this->lastname',email='$this->email'"); $this->id=mysql_insert_id(); } function update(){ mysql_query("UPDATE users SET firstname='$this- >firstname',lastname='$this->lastname',email='$this->email' WHERE id='$this->id'"); } function delete(){ mysql_query("DELETE FROM users WHERE id='$this->id'"); } }
Definitely, the "DBIGenerator" class does its thing building the corresponding database interface class for a specified database table. In this case, I'm showing a more readable version of the code generated, since in its obfuscated version, it doesn't contain any new lines. However, this is not a relevant issue for the PHP interpreter.
Well, happily we've seen how a simple code generator works, because we have a class that is capable of generating one or more classes, according to the particular application requirements. Do you realize the actual power of this approach? I guess you do. However, let's implement some examples to see how a database interface can be put to work for us.