PHP
  Home arrow PHP arrow Page 3 - Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2005-08-17


    Table of Contents:
  • Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables
  • Turning back time: a quick look at the older "DBIGenerator" class
  • Working with multiple database interfaces: improving the "DBIGenerator" class
  • Getting closer: a detailed look at the "generate()' method
  • Updating and deleting a row: the "update()" and "delete()" methods
  • Spotting the differences: the new "DBIGenerator" class in practice

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Building Object-Oriented Database Interfaces in PHP: Abstracting Database Tables - Working with multiple database interfaces: improving the "DBIGenerator" class
    ( Page 3 of 6 )

    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
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT