Dependency Injection is one of those programmer-y terms that sounds far more complicated than it is.
As defined in Wikipedia:
Dependency injection allows a program design to follow the dependency inversion principle. The client delegates to external code (the injector) the responsibility of providing its dependencies.
The client is not allowed to call the injector code. It is the injecting code that constructs the services and calls the client to inject them. This means the client code does not need to know about the injecting code.
But think about it like this (because if you’ve used object-oriented programming, you’ve no doubt done something like this):
- You have a class, say
Class Athat maintains a reference to another class,Class B. - In the constructor for
Class A, we instantiateClass Band set it equal to a property.
Easy enough, right? Here’s the implication:
Class A now has a dependency on Class B and that dependency is only set during the instantiation process in the constructor of Class A.
On a small scale, this isn’t that big of a deal but as a plugin or an application gets more and more complicated, there are all of these dependencies set in the system without any way to necessarily test them in isolation.
And don’t get me wrong: There should be some cohesion among objects in an application, but the degree to which they are coupled should be small. There are a lot of reasons for this many of which are outside the scope of this post.
To help mitigate this, programmers have created all kinds of strategies to make sure that our classes can be small and focused and tested in isolation all the while working with other parts of the system.
And one of the most popular ways to do this is through dependency injection. But what does dependency injection in WordPress look like (and is it any different than in other applications)?




