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 = 'alejandro@domain.com';
// create second user object $user2 = new User($db); $user2->name = 'Mary Smith'; $user2->email = 'mary@domain.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. Final thoughts 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. Don’t miss the upcoming part!
blog comments powered by Disqus |
|
|
|
|
|
|
|