Sunday, July 31, 2011

Dependency Injection Pattern using PHP

Behavioral Pattern – It is a technique that indicates to a part of a program which other parts it can use, i.e. to supply an external dependency, or reference, to a software component.

In technical terms, it is a design pattern that separates behavior from dependency resolution, thus decoupling highly dependent components.

// User.php
<?php
include_once('Database.php');
/**
 * Establishes a database connection and utilizes a singleton pattern
 * implementation to ensure only one instance exists during execution
 */
class User
{
    public function dbTask($db)
    {       
        $query = "SELECT name, age FROM student ";                       
        $result = $db->getQueryResult($query );
       
        while($thisrow = mysql_fetch_row($result))
        {
              $i=0;
              while ($i < mysql_num_fields($result))
              {
                $field_name = mysql_fetch_field($result, $i);
                echo $thisrow[$i] . " ";  //Display all the fields on one line
                $i++;
              }
            echo "<br>";  //put a break after each database entry
        }
    }
}
?>

// Calling.php
<?php
include_once('noUser.php');
// User and db is loosely coupled and dependency injected here between them
echo "Dependency Injection is applied"."<br><br>";
$user = new User();
$db = Database::getInstance();
$user->dbTask($db);
?>
Source: From lecture notes of Design and Development Open Multi-tier Application