John
John John has been developing websites and software for over 20 years. Focusing on Drupal over the last 12 years.

Drupal 8: Dependency Injection, what's that all about?

Drupal 8: Dependency Injection, what's that all about?

A big part of learning Drupal 8 and for some reason the one that took the longest for me to get my stoneage brain around is Dependency Injection. The title does sound a little daunting, coming from using Drupal 7 for quite a few years.

Once you grasp the principles of it, it becomes very clear how amazing it is.

Dependency Injection is an advanced software design pattern.

Benefits

  • Ensures decoupled functionality, which is more reusable.
  • Eases unit testing.
  • Is the preferred method for accessing and using services in Drupal 8.

Examples

Let’s have a look at some examples of Dependency Injection.

Current User

If we are writing hooks in a .module file and need to access the currently logged in user, we would tend to use the following code:

$current_user = \Drupal::currentUser();

However, if you were creating your controller class the preferred way is to inject the current user into your class rather than use the global Drupal class.

<?php

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * Controller for dashboard page.
 */
class DashboardController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * The current user account.
   *
   * @var \Drupal\Core\Session\AccountInterface
   */
  protected $currentUser;

  /**
   * {@inheritdoc}
   *
   * @param \Drupal\Core\Session\AccountInterface $account
   *   The current user account.
   */
  public function __construct(AccountInterface $account) {
    $this->currentUser = $account;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('current_user')
    );
  }

  /**
   * Method to display the dashboard page.
   */
  public function showDashboard() {
    // Get the current users name for display.
    $username = $this->currentUser->getDisplayName();

    // Return some markup for the dashboard page.
  }
}

To see what services are available to inject into your own classes, have a look in the core.services.yml file which is in the root of the /core folder. This will also assist you on what to enter into the create method.

If you have created your own custom classes or services, these can also be injected in the same way. I will cover using Dependency Injection in future articles when creating your own plugins or extending core classes.

Please leave a comment with any feedback or if you feel I have explained something incorrectly.

comments powered by Disqus