Document cases where it's appropriate to use global \Drupal calls as opposed to DI

Created on 9 December 2020, about 4 years ago
Updated 2 February 2024, 11 months ago

Problem/Motivation

General community consensus is that global \Drupal calls should never be used in OO code except in edge cases and scenarios where DI is not possible. However, this philosophy, its reasoning, and how it should be applied are not actually reflected clearly in our standards.

Proposed resolution

Compile a comprehensive list of situations where DI is not possible/appropriate and \Drupal calls are the only viable option, and add them to a handbook page along with information on why it's advisable to use DI when possible. Some potential cases brought up in the slack discussion on the topic:

@jhodgdon

Drupal is also used a lot in Functional tests.

@larowlan

Entities, field type plugins and data type plugins currently have no scope for DI

@mikelutz

\Drupal calls are also used in core to maintain backwards compatibility. We canโ€™t just add a new dependency injection, we have to make it optional, get it by \Drupal and throw a deprecation error if it isnโ€™t passed so that existing code continues to work, We can eventually make the parameter required in the next major version and remove the \Drupal call

@mxr576

adding a new parameter to a service as nullable, retrieving the service from \Drupal::service() if the parameter is null and triggering and error

I'll add that static methods were brought up a couple of times. But, unless the static class exists in one of the above contexts this feels like code smell and should probably be re-implemented in a service.

For entities, it would seem that https://www.drupal.org/project/drupal/issues/2142515 โ†’ is relevant.

๐Ÿ“Œ Task
Status

Active

Component

Coding Standards

Created by

๐Ÿ‡บ๐Ÿ‡ธUnited States mrweiner

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

  • ๐Ÿ‡ฎ๐Ÿ‡ณIndia ighosh

    Global \Drupal calls must be used and NOT DI (Dependency Injection) in every place where classes can't be used AND in static functions. Some examples of types of files where classes are not used - .install | .module. In all other situations, DI must be used. Do correct me if I made any mistake. Cheers!

  • ๐Ÿ‡ฆ๐Ÿ‡นAustria drunken monkey Vienna, Austria

    Global \Drupal calls must be used and NOT DI (Dependency Injection) in every place where classes can't be used AND in static functions. Some examples of types of files where classes are not used - .install | .module. In all other situations, DI must be used. Do correct me if I made any mistake. Cheers!

    There are lots of classes, like entity classes, where DI is currently not supported. See the issue summary.

Production build 0.71.5 2024