Home arrow PHP arrow Page 2 - Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables

Turning back time: a quick look at the older "DBIGenerator" class - PHP

Welcome to part two of the series "Building Object-Oriented Database Interfaces in PHP." In the previous article, I offered complete coverage of the role that database interfaces play in Web applications, highlighting the immediate benefits of having a centralized mechanism for accessing, processing and verifying data, within an object-oriented environment. The "DBIGenerator" class I showed for demonstration purposes in the first article doesn't scale well in real applications. In this article, we will start solving its problems with a revamped version of the class.

TABLE OF CONTENTS:
  1. Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables
  2. Turning back time: a quick look at the older "DBIGenerator" class
  3. Working with multiple database interfaces: improving the "DBIGenerator" class
  4. Getting closer: a detailed look at the "generate()' method
  5. Updating and deleting a row: the "update()" and "delete()" methods
  6. Spotting the differences: the new "DBIGenerator" class in practice
By: Alejandro Gervasio
Rating: starstarstarstarstar / 13
August 17, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

For the purpose of having a brief look at the definition of the original "DBIGenerator" class, and exemplifying specific DML operations, here's how the class looked:

class DBIGenerator{

// define data members

var $name;

var $path;

var $options;

function DBIGenerator
($name='DEFAULTNAME.php',$path='DEFAULTPATH/',$options=array
()){

$this->name=$name;

$this->path=$path;

$this->options=$options;

}

function create(){

// create class data members definition

$str='<?php'."\n";

$str.='class '.$this->name.'{'."\n";

foreach($this->options as $option){

$str.='var $'.$option.'=\'\';'."\n";

}

// create constructor

$str.='function '.$this->name.'(){}'."\n";

// create modifiers and accessors

foreach($this->options as $option){

$str.='function set'.$option.'($'.$option.'){'."\n";

$str.='$this->'.$option.'=$'.$option.';'."\n";

$str.='}'."\n";

$str.='function get'.$option.'(){'."\n";

$str.='return $this->'.$option.';'."\n";

$str.='}'."\n";

}

// create "submit()" method

$str.='function submit(&$db){'."\n";

// build insert query

$str.='$sql="INSERT INTO users SET ';

foreach($this->options as $option){

$str.=($option!='id')?$option.'=\'$this->'.$option.'\',':'';

}

$str.='";'."\n";

// remove trailing comma

$str=preg_replace("/,\"/","\"",$str);

// perform query

$str.='$db->performQuery($sql);'."\n";

$str.='$this->id=&$db->getInsertID();'."\n";

$str.='}'."\n";

// create "load" method

$str.='function load(&$db){'."\n";

// build query

$str.='$sql="SELECT * FROM users WHERE id=\'$this->id\'";'."\n";

// perform query

$str.='$result=$db->performQuery($sql);'."\n";

$str.='$row=$result->fetchRow();'."\n";

$str.='return $row;'."\n";

$str.='}'."\n";

// create "update" method

$str.='function update(&$db){'."\n";

// build query

$str.='$sql="UPDATE users SET ';

foreach($this->options as $option){

$str.=($option!='id')?$option.'=\'$this->'.$option.'\',':'';

}

// remove trailing comma

$str=preg_replace("/,$/","",$str);

$str.=' WHERE id=\'$this->id\'";'."\n";

// perform query

$str.='$db->performQuery($sql);'."\n";

$str.='}'."\n";

// create "delete" method

$str.='function delete(&$db){'."\n";

// build query

$str.='$sql="DELETE FROM users WHERE id=\'$this->id\'";'."\n";

// perform query

$str.='$db->performQuery($sql);'."\n";

$str.='}'."\n";

$str.='}?>';

// wite contents to class file

$fp=fopen($this->path.$this->name.'.php',"w") or die('Error
creating class file');

fwrite($fp,$str);

fclose($fp);

}

function getObject(){

// create object

if(file_exists($this->path.$this->name.'.php')){

require_once($this->path.$this->name.'.php');

return new $this->name;

}

return false;

}

}

Based on the above class, we're able to create several DB interface classes that operate directly on databases tables, allowing an efficient single-row manipulation. Again, let's implement an example to understand how DML statements are performed against a table:

// include class files

require_once 'mysqlclass.php';

require_once 'dbigeneratorclass.php';

// instantiate a new MySQLConnector object

$db=&new MySQLConnector(array
('host'=>'host','user'=>'user','password'=>
'password','database'=>'database'));

// set class properties-accessors and modifiers

$options=array('id','firstname','lastname','email');

// instantiate a DBI generator object

$gn=&new DBIGenerator('User','DBICLASSES/',$options);

// create User class

$gn->create();

// create user object

if(!$user=$gn->getObject()){

die('Failed to create object');

}

Here, we first included the required class files to connect to MySQL and spawned a "DBIGenerator" object, passing as parameters an array containing the names of the table fields that compose the structure of the sample "users" table (notice that this table is hard-coded within the class).

Then, once the $gn object has been created, we build a DB Interface class, named "User", which is located in the "DBICLASSES" directory, using the lines:

$gn=&new DBIGenerator('User','DBICLASSES/',$options);

// create User class

$gn->create();

The last thing to do is to get an $user object that is properly returned by the "getObject()" method. Now, since this object is a logical representation of the "users" table structure, we can easily insert, update or delete a row from it. How is it done? It's as simple as this:

// set user properties

$user->setfirstname('Homer');

$user->setlastname('Simpson');

$user->setemail('homer@springfield.com');

// insert row into database table

$user->submit($db);

echo 'Row '.$user->getid(). ' inserted successfully';

The above snippet adds a new user to the table. Simple, huh? Fine, now let's update a row:

$user->setfirstname('Lisa');

$user->setlastname('Simpson');

$user->setemail('lisa@springfield.com');

// update table row

$user->update($db);

echo 'Row updated successfully ';

Finally, let's delete the row:

// delete row

$user->delete($db);

echo 'Row deleted successfully';

Definitely, that was really easy. We've carried out single-row operations by using directly the interface provided by the $user object.

From the given examples, we can quickly understand that a singe DB interface is rather limited in its functionality. The actual power comes when multiple interfaces are grouped together to carry out a specific task. The big picture can be grasped pretty easily.

If we have multiple tables, where each one of them has a database interface tied to it, by combining them into an application, we're able to perform more complex operations on several tables at the same time. This changes the scenario dramatically, boosting the application considerably.

But, in fact, I'm getting ahead of myself. The big problem is that our "DBIGenerator" class only works with the predefined "users" database table. We should get rid of this big limitation, rewriting the class, in order to work with any supplied table. In the next section I'll show a new version of the class, which presents several improvements that solve these difficulties.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: