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
 * 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))
              while ($i < mysql_num_fields($result))
                $field_name = mysql_fetch_field($result, $i);
                echo $thisrow[$i] . " ";  //Display all the fields on one line
            echo "<br>";  //put a break after each database entry

// Calling.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();
Source: From lecture notes of Design and Development Open Multi-tier Application