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
https://www.drupal.org/docs/drupal-apis/services-and-dependency-injection/services-and-dependency-injection-in-drupal-8
Comments