Overview
Dependency injection is a programming technique that makes a class independent of its dependencies. It achieves that by decoupling the usage of an object from its creation.
Imagine you have class Page
which requires Request
and Permissions
in order to function. In the most naive implementation you might see something like the following:
class Page {
public function __construct() {
$this->request = new Request($arguments, $needed);
$this->permission = new Permissions($to, $construct, $these, $classes);
}
}
Now looking at this example we can see a few obvious pitfalls. In order to create the requests and permissions in our class need to know everything required to construct them. Even if we did know everything we needed, if they changed in the future, we would to be aware of what changed and update our implementation, even if we don't actually care about those details as part of our page.
Dependency is method of achieving Inversion of Control and the Single Responsibility Principle.
Our class doesn't really care about the details of the request and permissions are created. It only cares that we receive them.
So a simple fix is flip our example around, and get the request and permissions from somewhere else.
class Page {
public function __construct(Request $request, Permissions $permissions) {
$this->request = $request;
$this->permission = $permissions.
}
}
Dependency Injection Containers
A dependency injection container is some utility or library that attempts to simplify this pattern. Generally they have:
- Some way of declaring the dependencies of your class.
- A way of instantiating all of those dependencies, and their dependencies, and so on.
- A way of configuring shared rules for a dependency.
Garden\Container
garden-container is the dependency injection container used by Vanilla.
Read more information about its usage in Vanilla.
Resources