This is a note for myself to get to know more concrete details about Dependency Injection.
Dependency injection is a design pattern or at least “a set of patterns and principles; i.e. not a single pattern”. The intent behind dependency injection is to achieve separation of concerns of construction and use of objects.
- It is one form of the broader technique of inversion of control, which also includes service locator pattern, template method design pattern, etc.
- It implements Dependency inversion principle, which achieves loosely coupling and advocates using interface/abstraction rather than concrete implementations.
- One of its major benefits is to ease writing tests by using mocks/stubs for services used in clients.
This Wikipedia section is excellent in defining roles in dependency injection (their examples are great too):
- the service objects, which contain useful functionality
- the interfaces by which those services are known to other parts of the code
- the client object, whose behavior depends on the services it uses
- the injector, which constructs the services and injects them into the client
Three different types of depedency injections:
- Constructor injection
- Setter injection
- Interface injection
Some thoughts from Martin Fowler:
- Generally, Dependency Injection is better than Service Locator.
- The choice between them is less important than the principle of separating configuration from use.
- Prefer constructor injection over setter injection.
References:
- https://en.wikipedia.org/wiki/Dependency_injection
- https://stackoverflow.com/questions/66915874/is-dependency-injection-a-design-pattern
- https://stackoverflow.com/questions/46709170/difference-between-dependency-injection-and-dependency-inversion
- https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/src/README.md
- https://container.thephpleague.com/4.x/
- https://phptherightway.com/#dependency_injection
- https://www.php-fig.org/psr/psr-11/
- https://www.php-fig.org/psr/psr-11/meta/
- https://laravel.com/docs/8.x/container
- https://www.martinfowler.com/articles/injection.html
- Internal interesting comment: p5TWut-sl-p2#comment-1436
One thought on “Dependency Injection (plus Inversion of Control, and Dependency Inversion principle)”