Pour éviter la redondance de \drupal::service('monservice') dans nos classes, nous allons utiliser les injections de dépendances
Utiliser l’injection de dépendance dans un contrôleur
use Drupal\centreon_status\Service\CentreonStatus;
use Drupal\Core\PageCache\ResponsePolicy\KillSwitch;
/**
* Class ServicesController.
*/
class ServicesController extends ControllerBase {
/**
* CentreonStatus Service.
*
* @var \Drupal\centreon_status\Service\CentreonStatus
*/
protected $centreonstatus;
/**
* KillSwitch.
*
* @var \Drupal\Core\PageCache\ResponsePolicy\KillSwitch
*/
protected $killswitch;
/**
* HostsController constructor.
*
* @param \Drupal\centreon_status\Service\CentreonStatus $centreonStatus
* CentreonStatus.
* @param \Drupal\Core\PageCache\ResponsePolicy\KillSwitch $killswitch
* KillSwitch.
*/
public function __construct(CentreonStatus $centreonStatus, KillSwitch $killswitch) {
$this->centreonstatus = $centreonStatus;
$this->killswitch = $killswitch;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('centreon_status.centreon_status'),
$container->get('page_cache_kill_switch')
);
}
/**
* Get Content.
*
* @return array
* renderable array.
*/
public function getContent() {
[...]
$this->killswitch->trigger();
[...]
}
Utiliser l’injection de dépendance dans un plugin block
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\centreon_status\Service\CentreonStatus;
/**
* Provides a 'centreon_status' block.
*
* @Block(
* id = "centreon_hosts_status",
* admin_label = @Translation("Hosts status"),
* )
*/
class CentreonHostsBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* CentreonStatus service.
*
* @var \Drupal\centreon_status\Service\CentreonStatus
*/
protected $centreonstatus;
/**
* CentreonServicesBlock constructor.
*
* @param array $configuration
* @param string $plugin_id
* @param mixed $plugin_definition
* @param \Drupal\centreon_status\Service\CentreonStatus $centreonStatus
* CentreonStatus.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, CentreonStatus $centreonStatus) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->centreonstatus = $centreonStatus;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('centreon_status.centreon_status')
);
}
/**
* {@inheritdoc}
*/
public function build() {
[...]
var_dump($this->centreonstatus->getRealtime('hosts'));
[...]
}