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

Working with multiple database interfaces: improving the "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

So far, we've seen the significant limitations of the original class in real applications. Certainly, we need to develop a more flexible class that will be capable of generating multiple DB interfaces, in order to work with several database tables. Therefore, the brand new "DBIGenerator" class might be defined like this:

class DBIGenerator{

var $table;

var $name;

var $path;

function DBIGenerator
($table,$name='default_file.php',$path='DEFAULTPATH/'){

$this->table=$table;

$this->name=$name;

$this->path=$path;

}

function generate(){

// build class header

$str='<?php class '.$this->name.'{';

if(!$result=mysql_query("SHOW COLUMNS FROM $this->table")){

die('Could not run query '.mysql_error());

}

// build data member declaration

if(mysql_num_rows($result)>0){

while($row=mysql_fetch_array($result,MYSQL_ASSOC)){

$str.='var $'.$row['Field'].'=\'\';';

$methods.='function set'.$row['Field'].'($'.$row['Field'].')
{$this->'.$row['Field'].'=$'.$row['Field'].';}';

$methods.='function get'.$row['Field'].'(){return $this-
>'.$row['Field'].';}';

// store field names in array

$fields[]=$row['Field'];

}

}

// build empty constructor

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

// build modifiers and accesors

$str.=$methods;

unset($methods);

// build load() method

$str.='function load(){$r=mysql_query("SELECT * FROM
'.$this->table.' WHERE id=\'$this->id\'");';

$str.='return mysql_fetch_array($r,MYSQL_ASSOC);}';

// build submit() method

$str.='function submit(){mysql_query("INSERT INTO '.$this-
>table.' SET ';

foreach($fields as $field){

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

}

$str.='");$this->id=mysql_insert_id();';

$str=preg_replace("/,\"/","\"",$str).'}';

// build update() method

$str.='function update(){mysql_query("UPDATE '.$this-
>table.' SET ';

foreach($fields as $field){

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

}

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

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

// build delete() method

$str.='function delete(){mysql_query("DELETE FROM '.$this-
>table.' WHERE id=\'$this->id\'");}';

$str.='}?>';

// write class code to file

$fp=fopen($this->path.$this->name.'.php','w') or die('Failed
opening file');

fwrite($fp,$str);

fclose($fp);

// delete temporary variables

unset($fp,$str,$row,$fields,$field);

}

function getObject(){

// check if class file exists

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

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

// create object

return new $this->name;

}

return false;

}

}

Despite the fact that the source class code is quite long, its simplicity is remarkable. Taking a closer look at it, we can see that its logic is fairly similar to the previous version. Jumping straight into its code, the constructor takes three incoming parameters, described as follows: the first one $table represents the database table from which the database interface will be created. This single parameter implies a big improvement compared to the previous version, since it allows to rapidly generate a DB interface from any table passed to the class.

The second parameter $name, means the file name of the DB interface class to be created. Finally the third argument, $path, indicates the path within the file system where the class will be physically located. The constructor simply assigns these values as class properties, as we see below:

function DBIGenerator
($table,$name='default_file.php',$path='DEFAULTPATH/'){

$this->table=$table;

$this->name=$name;

$this->path=$path;

}

Again, I've specified default values for the name of the DB interface class, as well as for the path. As you can see, the constructor definition is closely similar to the old version.

The next thing to do is to explain the logic of the "generate()" method, which obviously takes charge of generating the DB interface class file, including the required methods to set up the access points to a given database table. Join me in the next section to learn how this is done.



 
 
>>> 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: