PHP
  Home arrow PHP arrow Page 2 - Abstracting Database Access Using Polymorphism with Objects in PHP 5
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

Abstracting Database Access Using Polymorphism with Objects in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 11
    2007-03-21


    Table of Contents:
  • Abstracting Database Access Using Polymorphism with Objects in PHP 5
  • What shouldn't be done when accessing distinct database systems
  • Using Polymorphism to create a database abstraction layer
  • Demonstrating the functionality of Polymorphism

  • 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


    Abstracting Database Access Using Polymorphism with Objects in PHP 5 - What shouldn't be done when accessing distinct database systems
    ( Page 2 of 4 )

    As I explained in the introduction, Polymorphism can be used in all sorts of clever ways to build smarter applications. But in this particular case, I'm going to demonstrate how to use it to create a simple -- yet robust -- database abstraction layer that can be utilized to access different database systems.

    However, I'm going to start on the opposite side. First I'll show you a poor implementation of a sample database abstraction layer, which will take care of working with MySQL and SQLite simultaneously. The key point is that this application isn't going to take advantage of Polymorphism.

    Having said that, please take a look at the signature of the following class. As I explained before, it  will be capable of using the two database systems previously mentioned. Here is how the class in question looks:

    // define 'DBHandler' class (poor implementation of a class and
    lack of Polymorphism)
    class DBHandler{
      
    private $db;
      
    private $result;
      
    private $mysqli;
      
    private $sqlite;
      
    public function __construct($db,$host,$user,$password,$database){
        
    if($db!='MySQL'&&$db!='SQLite'){
          
    throw new Exception('Invalid type of database class');
        
    }
        
    $this->db=$db;
        
    if($this->db=='MySQL'){
          
    $this->connectMySQL($host,$user,$password,$database);
        
    }
        
    else{
          
    $this->connectSQLite($database);
        
    }
      
    }
      
    // run query
       
    public function query($query){
        
    if($this->db=='MySQL'){
          
    $this->queryMySQL($query);
        
    }
        
    else{
          
    $this->querySQLite($query);
        
    }
       }
       // fetch row
      
    public function fetchRow(){
        
    if($this->db=='MySQL'){
          
    return $this->fetchRowMySQL();
        
    }
        
    else{
          
    return $this->fetchRowSQLite();
        
    }
      
    }
      
    // connect to MySQL
      
    private function connectMySQL($host,$user,$password,$database){
        
    $this->mysqli=new MySQLI($host,$user,$password,$database);
        
    if(mysqli_connect_errno()){
          
    throw new Exception('Error connecting to MySQL database
    server : '.$this->mysqli->error);
        
    }
      
    }
      
    // run query against MySQL database
      
    private function queryMySQL($query){
        
    if(!$this->result=$this->mysqli->query($query)){
          
    throw new Exception('Error running query '.$query.' :
    '.$this->mysqli->error);
        
    }
      
    }
      
    // fetch row from MySQL database table
      
    private function fetchRowMySQL(){
        
    return $this->result->fetch_array(MYSQL_ASSOC);
      
    }
      
    // create SQLite database
      
    private function connectSQLite($database){
        
    $this->sqlite=new SQLiteDatabase($database);
        
    // this statement should be executed only once
        
    $this->sqlite->query("BEGIN;
    CREATE TABLE users (id INTEGER(4) PRIMARY KEY, name CHAR(255),
    email CHAR(255));
    INSERT INTO users (id,name,email) VALUES
    (NULL,'User1','user1@domain.com');
    INSERT INTO users (id,name,email) VALUES
    (NULL,'User2','user2@domain.com');
    INSERT INTO users (id,name,email) VALUES
    (NULL,'User3','user3@domain.com');
    COMMIT;");
      
    }
       
    // run query against SQLite database table
      
    private function querySQLite($query){
        
    if(!$this->result=$this->sqlite->query($query)){
          
    throw new Exception('Error running query '.$query.' :
    '.$this->mysqli->error);
        
    }
      
    }
      
    // fetch row from SQLite database table
      
    private function fetchRowSQLite(){
        
    return $this->result->fetch(SQLITE_ASSOC);
      
    }
    } 

    If you take some time to carefully examine the definition of the above class, you'll see that it's been provided with the ability to perform a few useful tasks, like connecting either to MySQL or SQLite, in addition to running queries, fetching and counting database table rows in both database applications, and so on. Quite simple, right?

    In addition, a couple of examples on how to use this class are listed below:

    try{
      
    // use 'DBHandler' class (poorly implemented example)
      
    $dbh=new DBHandler('MySQL','host','user','password','database');
      
    $dbh->query('SELECT name,email FROM users');
      
    while($row=$dbh->fetchRow()){
        
    echo $row['name'].' '.$row['email'].'<br />';
      
    }
    }
    catch(Exception $e){
       echo $e->getMessage();
       exit();
    }

    try{
      
    // use 'DBHandler' class (poorly implemented example)
      
    $dbh=new DBHandler('SQLite','host','user','password','database');
      
    $dbh->query('SELECT name,email FROM users');
      
    while($row=$dbh->fetchRow()){
        
    echo $row['name'].' '.$row['email'].'<br />';
      
    }
    }
    catch(Exception $e){
      
    echo $e->getMessage();
      
    exit();
    }

    At first glance, the previous abstraction class seems to fit the requirements for working with both database systems. However, it should be noticed that the code used to perform this process is extremely inefficient.

    Why do I say this, if the prior class does what's expected? Well, if you study the respective definitions of many of its methods, you'll see that there's always a conditional statement that checks to see whether the used database system is MySQL or SQLite. This is really a poor approach from a development point of view, and certainly can be even worse if more methods are added to the original class. Imagine how much time will be wasted when updating this abstraction class!

    The previous class isn't taking advantage of Polymorphism. This feature could facilitate the maintainability of a complete database application. It could also noticeably improve the way that the different database systems are accessed.

    But, how can we take advantage of this feature in a truly useful fashion? To see how a simple database abstraction layer can be built using the functionality provided by a few polymorphic classes, you'll have to read the following section.



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

       

    PHP ARTICLES

    - Implementing Factory Methods in PHP 5
    - 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





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