HomePHP Injecting Objects Using Setter Methods with the Dependency Injection Design Pattern
Injecting Objects Using Setter Methods with the Dependency Injection Design Pattern
In this third article of a six-part series, you will learn how to implement the dependency injection pattern by using a simple setter method. This process is very similar to the one that uses a constructor, which we covered in the previous article.
One of the most common tasks that many PHP 5 programmers must tackle during the development of object-oriented web applications is defining the way that objects are going to interact with each other. While this process seems to be a no-brainer one at first sight, the truth is that in real-world conditions it can be an extremely challenging and daunting experience.
Sad but true, a small application initially conceived to use some scarce classes can quickly become a confusing, messy maze as it grows in size and complexity, where certain objects are responsible for creating other objects here and there, without any type of restriction or predefined order. If you’ve ever reached that point as a PHP developer, then you know that you’ve been knocking on hell’s doors.
Fortunately, there’s a proven solution for a situation like this, which is incredibly simple to implement, called dependency injection. As the name suggests, this pattern permits you to define, through a few straightforward approaches, the way that classes will take in their dependencies, without compromising class encapsulation.
Due to the schema imposed by this pattern, it actively promotes the application of the Inversion of Control principle. This principle dictates that the environment is always responsible for providing objects with their dependencies, and not the other way around.
Of course, if you already read the previous part of this series, then you have a clearer idea on how to use dependency injection when working with a database handler and a class that needs it to build persistent objects.
In that example in particular, the database handler (read the dependency) was passed to the persistent class via its constructor method, which is one of the simplest ways to implement the pattern. Though, as I said before, dependency injection can be accomplished by using several approaches, including one that uses a setter method to pass the dependency of a given object.
In the next few lines I’m going to explain how to translate this last approach to functional PHP 5 code. Now, let’s continue exploring the benefits of using the dependency injection pattern. Let’s go!