Home arrow PHP arrow Page 4 - The Dependency Injection Design Pattern in PHP 5

Changing the definition of the User class - PHP

In this first part of a six-part series, I introduce you to the dependency injection design pattern and its use with MySQL. Specifically, I create a typical scenario where one persistent class needs the functionality of its dependency, in this case a database handler, to gain access to a MySQL table.

  1. The Dependency Injection Design Pattern in PHP 5
  2. A basic MySQL-driven application with the dependency injection pattern
  3. Defining a basic factory method
  4. Changing the definition of the User class
By: Alejandro Gervasio
Rating: starstarstarstarstar / 5
October 08, 2009

print this article



Now that you grabbed the logic that drives the factory method defined inside the previous MySQL database handler, its time to tweak the definition of the User class so it can use this method to have access to its corresponding database table.

The following code sample shows the modified version of this class, which looks as follows:

class User


private $data = array();

private $id = NULL;

private $db = NULL;


// constructor

public function __construct($id = NULL)


$this->db = MySQL::factory('host', 'user', 'password', 'database');

 if ($id !== NULL)


$this->id = $id;

$this->db->query('SELECT * FROM users WHERE id=' . $this->id);

$this->data = $this->db->fetch();




// set undeclared property

public function __set($property, $value)


if ($property !== 'name' and $property !== 'email')




$this->data[$property] = $value;



// get undeclared property

public function __get($property)


if (isset($this->data[$property]) === TRUE)


return $this->data[$property];




// save object to session variable

public function __destruct()


if ($this->id === NULL)


$this->db->query("INSERT INTO users (id, name, email) VALUES (NULL, '$this->name', '$this->email')");




$this->db->query("UPDATE users SET name = '$this->name', email = '$this->email' WHERE id = $this->id");




There you have it. Now the constructor of the persistent User class internally calls the factory method provided by MySQL to have access to its storage table. In this case, the relationship established between these classes has been slightly improved by simply refactoring the constructor of the first one.

Of course, Im not saying that this is an ideal situation, but with this small change its possible to build the pair of persistent objects that you saw previously using the same script. Take a look at it:

// create a user object

$user1 = new User();

$user1->name = 'Alejandro Gervasio';

$user1->email = 'alejandro@domain.com';


// create another user object

$user2 = new User();

$user2->name = 'Mary Smith';

$user2->email = 'mary@domain.com';

Building two persistent objects took literall six lines of code, apart from the comments, which is not too bad at all, huh? Naturally, the most interesting things are happening behind that short code sample, since the objects now share a single instance of the database handler for storing and retrieving their properties.

This is a neat example that shows in a nutshell how useful Singletons can be when it comes to optimizing the creation of objects, even though this process, in this particular case, occurs in the wrong place. But not all is lost; thanks to the functionality given by the dependency injection pattern, its possible to solve this issue in a really simple way. 

Learning how to implement this pattern will be the topic of the next tutorial. Meanwhile, keep yourself entertained by editing the examples shown in this one. 

Final thoughts

In this introductory chapter of the series, I recreated a typical scenario where one persistent class needed the functionality of its dependency, in this case a database handler, to gain access to a MySQL table. Even though all of the examples that you saw before worked decently well, in all of them the instantiation of the dependency was a responsibility of the persistent class, which isnt good, because its breaks up encapsulation.

Of course, its possible to quickly fix this issue by taking advantage of the functionality of the dependency injection pattern. Therefore, if you wish to learn how this pattern will be applied in conjunction with the aforementioned classes, then dont miss the next article!

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

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: