Services and dependency injection in Drupal 8

Dependency Injection enables us to decouple reusable functionality by injecting it, rather than creating it inside of a class.

Drupal 8 introduces the concept of services to decouple reusable functionality and makes these services pluggable and replaceable by registering them with a service container.

Dependency injection is an alternative to the static \Drupal::service

There are, at least, two widely spread patterns in Drupal 8 in order to inject services into your objects. The first uses a service to inject services. The second uses a factory method that receives Drupal's container.

For Example:

modules/custom/thirstysix/thirstysix.info.yml

name: Thirsty Six Custom Module
description: Custom Module
type: module
version: 8.x-1.0
core: 8.x

 

modules/custom/thirstysix/thirstysix.services.yml

services:
  thirstysix.ex:
    class: Drupal\thirstysix\Customservice
    arguments: ['@current_user']

 

modules/custom/thirstysix/src/Customservice.php

<?php
  namespace Drupal\thirstysix;
  
  use Drupal\Core\Session\AccountProxy;

  /**
   * Drupal 8 service.
   */
  class Customservice {

    private $currentUser;

    /**
     * DependencyInjection.
     */
    public function __construct(AccountProxy $currentUser) {
      $this->currentUser = $currentUser;
    }

    /**
     * Returns a current Drupal user name.
     */
    public function DisplayUserName() {
      return $this->currentUser->getDisplayName();
    }

  }

 

Print:

 $service = \Drupal::service('thirstysix.ex');
 kint($service->DisplayUserName());
Tags

Add new comment

Restricted HTML

  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
1 + 10 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.