PHP
  Home arrow PHP arrow Page 3 - The Dependency Injection Design Pattern 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

The Dependency Injection Design Pattern in PHP 5
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 4
    2009-10-08


    Table of Contents:
  • The Dependency Injection Design Pattern in PHP 5
  • A basic MySQL-driven application with the dependency injection pattern
  • Defining a basic factory method
  • Changing the definition of the User class

  • 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


    The Dependency Injection Design Pattern in PHP 5 - Defining a basic factory method
    (Page 3 of 4 )

    Frankly speaking, the best way to define a relationship between the previous “User” class and its dependency, that is the database handler, is by applying the dependency injection pattern. Nonetheless, at least for the moment I’m going to introduce a couple of modifications to these classes, so they can interact with each other in a more efficient manner.

    First, the “MySQL” class will expose a brand new method, called “factory(),” which will return to client code a Singleton instance of the class.

    The improved definition of this class now looks as follows:

    class MySQL

    {

    private $result = NULL;

    private $link = NULL;

    private static $instance = NULL;

     

    // returns a singleton instance of MySQL class (chainable)

    public static function factory($host, $user, $password, $database)

    {

    if (self::$instance === NULL)

    {

    self::$instance = new MySQL($host, $user, $password, $database);

    }

    return self::$instance;

    }

    // connect to MySQL

    public function __construct($host, $user, $password, $database)

    {

    if (FALSE === ($this->link = mysqli_connect($host, $user, $password, $database)))

    {

    throw new Exception('Error : ' . mysqli_connect_error());

    }

    }

     

    // perform query

    public function query($query)

    {

    if (is_string($query) AND empty($query) === FALSE)

    {

    if (FALSE === ($this->result = mysqli_query($this->link, $query)))

    {

    throw new Exception('Error performing query ' . $query . ' Error message :' .mysqli_error($this->link));

    }

    }

    }

     

    // fetch row from result set

    public function fetch()

    {

    if (FALSE === ($row = mysqli_fetch_assoc($this->result)))

    {

    mysqli_free_result($this->result);

    return FALSE;

    }

    return $row;

    }

     

    // get insertion ID

    public function getInsertID()

    {

    return mysqli_insert_id($this->link);

    }

    // count rows in result set

    public function countRows()

    {

    if ($this->result !== NULL)

    {

    return mysqli_num_rows($this->result);

    }

    }

    // implement destructor to close the database connection

    function __destruct()

    {

    mysqli_close($this->link);

    }

    }

    As I said before, the brand new “factory()” method added to the above “MySQL” class is simply responsible for returning Singletons of the class in question. It has been declared static for obvious reasons, since it uses the static “$instance” property to reduce to one the number of class instances created within a given script.

    As you can see, the implementation of this factory method is straightforward and easy to follow, and additionally ensures that, if the “User” class calls it inside its context, only one single instance of the database handler will be returned.

    Even though this method is not a truly clean solution that solves the dependency-related issue that exists between both “User” and “MySQL” classes, it does help to implement their relationship in a more efficient way.

    However, the next step that must be taken to complete this improvement process is to change the definition of the “User” class, so it can take advantage of the factory method discussed a moment ago.

    This modification will be discussed in the last section of this tutorial, so to learn more about it, click on the link below and read the next few lines.



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

       

    PHP ARTICLES

    - The Iterator, Countable and ArrayAccess SPL ...
    - Implementing the Data Mapper Design Pattern ...
    - Defining an Abstract Class with Restrictive ...
    - The Reflection API: Working with Reflected M...
    - Using Restrictive Constructors in PHP 5
    - Getting Information on a Reflected Class wit...
    - Introducing the Reflection API in PHP 5
    - Swift Mailer's Batchsend Method and Other Fe...
    - Embedding Attachments into Email Messages wi...
    - Dynamically Attaching Files with Swift Mailer
    - Using Different Paths for Attachments with S...
    - Handling Attachments and Sending HTML Email ...
    - Sending Blind Carbon Copies with Swift Mailer
    - Using Swift Mailer's Cc MIME Header
    - Using Sendmail and Mail() with Swift Mailer


    Code Analysis Tools
    Enterprise code analysis tools that deliver quality and reliable code

     


     


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