HomePHP Page 4 - Injecting Objects by Constructor with the Dependency Injection Pattern
The dependency injection pattern in action - PHP
While not being as widely known as other design patterns such as Factory, Singleton or Active Record, the Dependency Injection pattern provides both programmers and web developers with a well-structured solution that allows them to solve issues that arise when an object needs the functionality of another one (hence the dependency) to work as expected. This is the second part of a six-part series that shows you how to apply this pattern.
As I anticipated in the previous segment, the only thing that remains undone here is building a script that shows how to create a couple of persisting objects, after improving the definition of the originating class.
With that idea in mind, I wrote that script, and it appears below. Take a look at the following fragment, please:
// example of dependency injection via the constructor
// create instance of MySQL class
$db = new MySQL('host', 'user', 'password', 'database');
// create first user object
$user1 = new User($db);
$user1->name = 'Alejandro Gervasio';
$user1->email = 'firstname.lastname@example.org';
// create second user object
$user2 = new User($db);
$user2->name = 'Mary Smith';
$user2->email = 'email@example.com';
Simple to code and read, isnít it? Quite possibly, the previous script isnít going to change the way that you develop your PHP 5 applications forever, but it shows in a nutshell how beneficial dependency injection can be when it comes to building programs where the context is responsible for providing the required dependencies to its objects, and not the opposite.
And with last code sample, Iím finishing this second episode of the series on applying the Dependency Injection pattern in PHP 5. As usual, feel free to edit all of the examples included in this tutorial, so you can develop a better understanding on this rather overlooked pattern.
Over this second part of the series, you learned how to implement a specific version of the dependency injection pattern, commonly called ďinjection by constructor.Ē As its name suggests, this approach injects the dependency directly through the constructor of the receiver object. Itís just that simple.
In the next installment, Iím going to teach you how to apply the Dependency Injection pattern in its other flavor, which simply passes the corresponding dependency via a setter method.