Dependency Injection is a design pattern that injects objects into the constructor or methods of other objects, so that one object depends on one or more other objects.
Lets first look at the example.
In the example above, we import two models Album
and Gallery
. We inject the models into our controller construct method. This means that, when this controller is called or executed, these two models are instantiated automatically without defining explicitly.
Types of Dependency Injection
There are three types of dependency injection.
- Constructor Injection
- Setter Injection
- Interface Injection
Constructor Injection
The type of Dependency Injection explained above is called Constructor Injection. That simply means that dependencies are passed as arguments to the classes constructor. The dependencies are then stored as properties and thus made available in all methods of the class. The big advantage here is, that a object of the class cannot exist without passing the dependencies.
In the example above, we cannot construct a new object of this class without passing Gallery and Album dependencies.
Setter Injection
Dependencies have to be passed into the class using setter methods. The advantage of using Setter Injection is, that you can add dependencies to an object after it has been created. It’s commonly used for optional dependencies. In other words, this can be used when the core functionality of the class does not rely on the dependency to work.
The object can be instantiated without any dependencies. There is a method to inject the dependency (setLogger()) which can be called optionally. Now it’s up to the methods implementation to either make use of the dependency or not (if it’s not set).
Interface Injection
The idea of interface injection is basically, that the method(s) to inject a dependency is defined in an interface. The class that is going to need the dependency must implement the interface.
In the above example, we defined a new InjectLoggerInterface
interface. We extend this interface in class A
whenever want the dependency.