#! code: Drupal 9: An Introduction To Services And Dependency Injection

Drupal 8 and 9 are built upon services, with many parts of the system available through dependency injection, so it’s important to understand the concepts. Services are a way to wrap objects and use dependency injection to produce a common interface. They are powerful and are used all over Drupal to do pretty much everything.

They can, however, be a little difficult for newcomers to the system to understand, especially if they are coming from Drupal 7 or other non-object oriented systems. When you look at some Drupal source code you are likely to see objects being created out of apparent thin air. It’s a little hard to know where they come from if you aren’t used to the how they work.

I first came across services when I started using Drupal 8 and it took me a little while to get my head around what they are and what they do. Before I understood them, I saw a lot of people online attempting to help by just pointing people to one service or another using this sort of construct.

$thing = Drupal::service('thing');

This is helpful if you are familiar with Drupal services, but if you aren’t then this doesn’t tell you much. It is also bad practice to use this construct in certain situations, which I’ll let into later on. If you have seen that construct around the internet but don’t know what it means then I hope to clear things up a little.

Read more.


Go to Source
Author: