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.

TABLE OF CONTENTS:
  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
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement
 

Now that you grabbed the logic that drives the factory method defined inside the previous “MySQL” database handler, it’s 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')

{

return;

}

$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')");

}

else

{

$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, I’m not saying that this is an ideal situation, but with this small change it’s 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, it’s 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 isn’t good, because it’s breaks up encapsulation.

Of course, it’s 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 don’t miss the next article!



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

blog comments powered by Disqus
   

PHP ARTICLES

- 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...
- PHP: Building Concrete Validators
- Sanitizing Input with PHP
- Executing Shell Commands with PHP
- Handling File Data with PHP
- File Security and Resources with PHP
- ArrayObject PHP Class Examples
- ArrayObject PHP Class: An Introduction
- Getting File System Data with PHP
- PHP Tools for Working with the File and Oper...
- Working with the File and Operating System w...
- PHP Proxy Patterns: Completing a Blog


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap

Dev Shed Tutorial Topics: