Author:
Source
I have been using the Drupal dependency injection system for a while now, even giving talks and writing articles on the subject. As the release of Drupal 10 is just around the corner I have been thinking more about how to override dependencies to plugin classes.
I wanted to share a trick to overriding dependency injection that will make your life easier. The Drupal codebase itself does not use this trick, but it seems that many contributed modules have started to use this trick to create plugin classes.
In this article I will go through how to add dependency injection to Drupal classes in two different patterns.
The first pattern will create problems and will require quite a bit more typing and repeating of code. The second pattern is much easier to use and will make life easier going forward.
An Example Block
The following block of code shows a very basic Drupal Block class that doesn’t do anything. This will be the basis of the rest of this article.
What I am going to do with this block is inject a service to perform route matching. In Drupal there are a couple of services to do this, but I will be using the current_route_match service to look for the service.