Skip to main content

Drupal Dependency Injection: Controllers

Back-end Development
Drupal

I am writing a Drupal module that has a controller for displaying a page. I want to use a service in my code. What's the correct way to access that service?

Drupal controllers already extend from ControllerBase, which implements ContainerInjectionInterface. To inject services, you will need to override that class's create method.

public static function create(ContainerInterface $container) {
 $controller = parent::create($container);
 ...
 return $controller;
}

Within the create method, you will call $container->get() for each service you need, and store the result in an instance variable for later use.

For example:

<?php

namespace Drupal\services_examples;

use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Datetime\DateFormatterInterface;

/**
 * A simple example of a service.
 */
class ExampleService implements ExampleServiceInterface {

  /**
   * The date formatter service.
   *
   * @var \Drupal\Core\Datetime\DateFormatterInterface
   */
  protected DateFormatterInterface $dateFormatter;

  /**
   * The time service.
   *
   * @var \Drupal\Component\Datetime\TimeInterface
   */
  protected TimeInterface $timeService;

  /**
   * Create a new ExampleService.
   */
  public function __construct(DateFormatterInterface $dateFormatter, TimeInterface $timeService) {
    $this->dateFormatter = $dateFormatter;
    $this->timeService = $timeService;
  }

  /**
   * {@inheritdoc}
   */
  public function getCurrentDate() : string {
    return $this->dateFormatter->format($this->timeService->getRequestTime());
  }

}

By implementing the constructor appropriately, we can gain access to any Drupal service we may need!