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());
- 912 views
Add new comment