Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 37 ยท Modules and Hooks

Services and Dependency Injection

Understand the Drupal service container: define services in services.yml, inject dependencies, use core services like entity_type.manager, and test with a container stand-in.

Almost everything useful in Drupal is a service: the database connection, the current user, the logger, the entity type manager, the mailer, the cache. A service is a PHP object created by the service container the first time somebody asks for it and then shared. Instead of reaching out with global functions, your classes receive the services they need through their constructor. That is dependency injection (DI), and it makes code testable and replaceable.

The code is read-only (Drupal cannot run here). The TryIt blocks implement a small container so you can watch injection, lazy creation and replacing services.

Defining a service

In tutorial_notes.services.yml:

YAML
services:
  tutorial_notes.note_manager:
    class: Drupal\tutorial_notes\NoteManager
    arguments:
      - '@entity_type.manager'
      - '@current_user'
      - '@logger.channel.tutorial_notes'
      - '@datetime.time'

  logger.channel.tutorial_notes:
    parent: logger.channel_base
    arguments: ['tutorial_notes']

Names beginning with @ refer to other services. The container builds entity_type.manager and the rest, then passes them to your constructor in that order.

PHP
<?php

namespace Drupal\tutorial_notes;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Psr\Log\LoggerInterface;

class NoteManager {

  public function __construct(
    protected EntityTypeManagerInterface $entityTypeManager,
    protected AccountInterface $currentUser,
    protected LoggerInterface $logger,
    protected TimeInterface $time,
  ) {}

  public function latestFor(int $limit = 5): array {
    $storage = $this->entityTypeManager->getStorage('node');
    $ids = $storage->getQuery()
      ->accessCheck(TRUE)
      ->condition('type', 'note')
      ->condition('uid', $this->currentUser->id())
      ->sort('created', 'DESC')
      ->range(0, $limit)
      ->execute();
    return $storage->loadMultiple($ids);
  }

}

Notice there is no \Drupal:: call inside. The class depends only on interfaces, so a unit test can pass fakes.

Node.js Stand-in: a service container with lazy creation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Getting services into classes

The container injects services into things it creates. For classes created by Drupal rather than from services.yml, you use a factory method:

PHP
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;

class NotesController extends ControllerBase {

  public function __construct(protected NoteManager $noteManager) {}

  public static function create(ContainerInterface $container): static {
    return new static($container->get('tutorial_notes.note_manager'));
  }

}

The same create() pattern appears in forms (ContainerInjectionInterface), plugins (ContainerFactoryPluginInterface::create() with extra plugin arguments) and blocks. In newer Drupal versions, controllers and plugins may use autowiring, where you only type-hint the class and Drupal finds the service.

When you cannot use DI (a procedural .module hook, a quick drush php:script), you can fall back on the static helper, but keep it out of classes:

PHP
$user = \Drupal::currentUser();
$time = \Drupal::time()->getRequestTime();
$node = \Drupal::entityTypeManager()->getStorage('node')->load(1);

Core services worth knowing

  • entity_type.manager: load and query entities. entity_field.manager, entity.repository.
  • current_user, current_route_match, request_stack.
  • database: the query builder ($connection->select('node_field_data', 'n')), prefer entity queries when possible.
  • config.factory: read and write configuration. state: environment-specific values. keyvalue.
  • logger.factory, messenger, string_translation, datetime.time, date.formatter.
  • cache.default, cache_tags.invalidator, renderer.
  • module_handler, plugin.manager.block, file_system, mail: manager plugins.

Decorating and replacing services

A service can be replaced or wrapped without editing the original:

YAML
services:
  tutorial_notes.rounded_time:
    class: Drupal\tutorial_notes\RoundedTime
    decorates: datetime.time
    arguments: ['@tutorial_notes.rounded_time.inner']

Because everyone asks the container for datetime.time, all code now receives your decorator. A service provider class (TutorialNotesServiceProvider::alter()) can also change definitions programmatically. Use this sparingly: the effect is site-wide.

Node.js Stand-in: decorating a service

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Tagged services

Tags let a service register with a collector. event_subscriber (see hooks and events), access_check, cache.bin, twig.extension and normalizer are tags. Your own module can define a tagged-services collector, which is how plugin-like extension points are built without the plugin system.

Testing with fakes

Because dependencies come through the constructor, a unit test builds the class with simple stand-ins: a prophesized EntityTypeManagerInterface, a stub user with ID 7. Tests that need the real database use kernel tests (KernelTestBase), which boot a minimal container. See Drupal's core/tests for patterns.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where do you define a custom service?

    Services are declared under the services key in MODULE.services.yml.
  2. 2. What does "@current_user" in arguments mean?

    The at sign marks a reference to another service.
  3. 3. Why prefer constructor injection over \Drupal::service() inside a class?

    DI makes dependencies visible and enables unit tests with fakes.
  4. 4. When is a service object created?

    Services are lazy and shared within a request.

Summary

  • Services are shared objects created lazily by the container and declared in MODULE.services.yml.
  • Inject them through constructors; use create() for controllers, forms and plugins.
  • Learn the core services: entity type manager, current user, config factory, logger, cache.
  • Decorate to change behaviour site-wide without editing code.
  • \Drupal:: static calls are for procedural code only.

Next: Plugins and Block Plugins