PHP
  Home arrow PHP arrow Page 2 - 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? 
Google.com  
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 - Turning back time: a quick look at the older "DBIGenerator" class
    ( Page 2 of 6 )

    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
     

       

    PHP ARTICLES

    - Merging a File Split for FTP Upload using PHP
    - Getting Data from Yahoo Site Explorer Inboun...
    - Method Chaining: Adding More Selecting Metho...
    - How to Split a File During an FTP Upload Usi...
    - Expanding a Custom CodeIgniter Library with ...
    - Using the Yahoo Site Explorer Inbound Links ...
    - Building a CodeIgniter Custom Library with M...
    - Building an E-mini Trading System Using PHP ...
    - Completing the MySQL Class with Method Chain...
    - 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 ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek