PHP
  Home arrow PHP arrow Page 3 - Abstracting Database Access Using Poly...
Dev Shed Forums 
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Forums Sitemap 
IBM® developerWorks 
Sun Developer Network 
Dedicated Servers 
E-Commerce Hosting 
Linux Web Hosting 
Managed Hosting 
Small Business Hosting 
Moblin 
JMSL Numerical Library 
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

Abstracting Database Access Using Polymorphism with Objects in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 10
    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:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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 - Using Polymorphism to create a database abstraction layer


    (Page 3 of 4 )

    In the previous section you saw how a simple database abstraction layer can be created to access both MySQL and SQLite systems. However, the major drawback with this class was the poor implementation presented for many of its methods, since none of them used Polymorphism to improve the way that database systems are accessed.

    Considering this issue, I'm going to define a new set of classes, which this time will take advantage of Polymorphism to work with the two database systems.

    Having said that, here is the signature of the first class that I plan to create in this section. This one is simply an abstract interface, from which I'll derive a couple of subclasses for working specifically with MySQL and SQLite.

    This abstract class looks like this:

    // define abstract 'DBConnector' class
    abstract class DBConnector{
      
    abstract public function __construct($host,$user,$password,$database);
      
    abstract public function query($query);
      
    abstract public function fetchRow();
      
    abstract public function countRows();
    }

    As you can see, the above abstract class is indeed very easy to follow, since it's merely an interface that defines generically the methods that will be implemented later by the respective subclasses.

    As I stated before, these subclasses will be responsible for working specifically either with MySQL or SQLite. Let me show you the corresponding signatures for each of them. Here they are:

    // define concrete 'MySQL' class
    class MySQL extends DBConnector{
      
    private $mysqli;
      
    private $result;
      
    // connect to MySQL
      
    public function __construct($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 database
      
    public function query($query){
        
    if(!$this->result=$this->mysqli->query($query)){
          
    throw new Exception('Error running query '.$query.' :
    '.$this->mysqli->error);
        
    }
      
    }
      
    // fetch database table row
      
    public function fetchRow(){
        
    return $this->result->fetch_array(MYSQL_ASSOC);
      
    }
      
    // count database table rows
       
    public function countRows(){
        
    if(!$rows=$this->result->num_rows){
          
    return 'No database rows were returned by the query';
        
    }
        
    return $rows;
      
    }
    }

    // define concrete 'SQLite' class
    class SQLite extends DBConnector{
      
    private $sqlite;
      
    private $result;
      
    public function __construct($host,$user,$password,$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 database
      
    public function query($query){
        
    if(!$this->result=$this->sqlite->query($query)){
          
    throw new Exception('Error running query '.$query.' :
    '.$this->sqlite->error);
        
    }
      
    }
      
    // fetch database table row
      
    public function fetchRow(){
        
    return $this->result->fetch(SQLITE_ASSOC);
      
    }
      
    // count database table rows
      
    public function countRows(){
        
    if(!$rows=$this->result->numRows()){
          
    return 'No database rows were returned by the query';
        
    }
        
    return $rows;
      
    }
    }

    Definitely, things are getting really exciting now! As you can see, the two subclasses listed above present the same methods (remember that they were derived from the parent "DBConnector"), but in this case each of them is implemented differently so they can work with either MySQL or SQLite.

    Of course, defining these child classes in this way implies having two completely independent structures, which can be easily updated with minor hassles. Nonetheless, the most important thing to note here is that I created two polymorphic classes, since they belong to the same family of objects, but behave differently using the same methods. Quite good, right?

    Having these handy polymorphic classes at our disposal, it's possible to create highly expansible database abstraction layers. If a new database system needs to be added to the layer in question, the process is reduced only to deriving the concrete subclass that deals with that specific system. Period.

    However, you may be wondering…how does a given application know which class to use according to the type of database system being utilized? The answer is that it simply uses a factory class that returns to client code the correct type of object to work with MySQL, SQLite or whatever system you may want to incorporate into your application.

    To demonstrate the previous concept, below I included the signature of a simple factory class. As I said before, it is tasked with spawning the correct type of database object, according to the database requirements of a specific application.

    Given that, here's how this brand new class looks:

    // define 'DBFactory' class
    class DBFactory{
      
    // create database class instance
      
    public function createDB
    ($db,$host='',$user='',$password='',$database='db.sqlite'){
        
    if($db!='MySQL'&&$db!='SQLite'){
          
    throw new Exception('Invalid type of database class');
        
    }
        
    return new $db($host,$user,$password,$database);
      
    }
    }

    Wasn't that simple? I bet it was! As you can see, the above factory class implements the required logic to create two specified database objects for working with MySQL and SQLite. Logically, after instantiating the correct type of object, the procedure for handling a given database system is only a matter of using its respective methods.

    Now, do you realize the convenience of working with polymorphic objects? I hope you do.

    Okay, having defined the group of classes required to implement this simple database abstraction layer, it's time to leap forward and develop a functional example, where all these classes will be put to work in conjunction. Doing so, you'll have a better idea of how Polymorphism can play a relevant role when using multiple database systems.

    To see how the previously defined classes will be used together in the same practical example, keep reading.

    More PHP Articles
    More By Alejandro Gervasio


       · In this first article of the series, the concept of Polymorphism is used to create a...
       · I think you made a conceptual mistake in your exemple...You should not have...
       · Hello Fred,Thank you for your posting your comments. However, mi article doesn’t...
       · I've read almost all your articles regarding php and oop.This one is by far the...
       · I'm going to disagree with you both here. First, abstract classes also lead to...
       · Thank you for your compliments on my PHP article. I indeed appreciate them, and also...
       · Hello Pim,First off, thank you for posting your comments here, since I believe...
     

       

    PHP ARTICLES

    - Building a Database-Driven Application with ...
    - User Authentication for a Project Management...
    - Introduction to the CodeIgniter PHP Framework
    - Adding Users for a Project Management Applic...
    - Migrating Class Code for a MIME Email to PHP...
    - Login and Logout Authentication for a Projec...
    - Composing Messages in HTML for MIME Email wi...
    - Project Management: Authentication
    - A Better Way to Determine MIME Types for MIM...
    - Project Management Overview
    - Handling Attachments in MIME Email with PHP
    - Completing the Project Management Application
    - Sending MIME Email with PHP
    - Handling Files for a Project Management Appl...
    - Viewing and Editing Tasks for a Project Mana...





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 4 hosted by Hostway