Use Drupal 8 Service and Dependency Injection

Submitted by editor on Thu, 10/13/2016 - 12:06
Question

How to use Drupal 8 Service and Dependency Injection ?

You can call drupal 8 services statically as D7, but it is not the best practice (Like Here).
Example : $uuid = \Drupal::service('uuid')->generate();
But it is not recommended, except on procedural scripts like .module .install ...

 

How to use Drupal 8 Service and Dependency Injection

Here we use the module created previously.
Example 1:

<?php
namespace Drupal\mytest\Controller;
use Drupal\mytest\MTService;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
 * Controller routines for page example routes.
 */
class TestDI extends ControllerBase {
  /**
   * @var \Drupal\mytest\MTService
   */
  protected $MTService;
  /**
   * {@inheritdoc}
   */
  public function __construct(MTService $MTService) {
    $this->MTService = $MTService;
  }
  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('mytest')
    );
  }
  public function tests() {
    $output = array();
    $html = "Get Test service :" . $this->MTService->run();
    $output[] = ['#markup' => $html];
    return $output;
  }
}

 

Example 2 :
Note : Works, but not the best way.

<?php

namespace Drupal\mytest\Controller;
use Drupal\Core\Controller\ControllerBase;

/**
 * Controller for DI example.
 */
class TestDI extends ControllerBase {

  public function tests() {
    $output = array();
    $html = "";
    $html .= "<br> Get new UUID : " . $this->getUUID();
    $html .= "<br> Get Test service : (display using kint)";
    kint($this->getTS());

    $output[] = array(
      '#markup' => $html,
      '#cache' => ['disabled' => TRUE]
    );

    return $output;
  }

  /**
   * Returns A new UUID.
   *
   * @return string
   *  new UUID
   */
  protected function getUUID() {
    return $this->container()->get('uuid')->generate();
  }

  /**
   * Return the 'Test Service'.
   *
   * @return string
   *  new UUID
   */
  protected function getTS() {
    return $this->container()->get('mytest');
  }

  /**
   * @inheritdoc
   */
  private function container() {
    return \Drupal::getContainer();
  }
}

 

...

More : https://docs.acquia.com/articles/drupal-8-dependency-injection

Add new comment

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image.