What is dependency injection in Drupal?

Dependency injection is a design pattern where objects receive their dependencies from an external source rather than creating them internally. Drupal uses Symfony’s service container to manage this.

Instead of calling a service statically, you declare it as a dependency in your class constructor or factory method. The container handles wiring everything up at runtime.

This approach makes code more testable, more modular, and easier to maintain. You can swap implementations without changing the code that uses them, which matters for unit testing and extending functionality. All new Drupal code should use dependency injection rather than the older pattern of calling services statically. For example, inject the entity type manager service rather than calling Drupal entityTypeManager directly. Once you get used to it, dependency injection becomes second nature.

Facebook
Twitter
LinkedIn
Pinterest