On this page
Dependency Injection
Last updated on
12 December 2023
Overview
Dependency Injection can be accomplished by using the same strategy you would in Block Plugins.
Below is an example of a class with Dependency Injection in practice.
<?php
namespace Drupal\MY_THEME\Plugin\preprocessors;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\preprocessors\PreprocessorPluginBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provide plugin to alter variables for nodes.
*/
final class NodePreprocessor extends PreprocessorPluginBase implements ContainerFactoryPluginInterface {
/**
* The ConfigFactory service.
*
* @var \Drupal\Core\Config\ConfigFactoryInterface
*/
protected ConfigFactoryInterface $configFactory;
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) : static {
$instance = new static($configuration, $plugin_id, $plugin_definition);
$instance->configFactory = $container->get('config.factory');
return $instance;
}
/**
* Add personal tweaks to variables in this function.
*
* {@inheritdoc}
*/
public function preprocess(array &$variables, string $hook, array $info) : void {
$defaultTheme = $this->configFactory->get('system.theme')->get('default');
$variables['defaultTheme'] = $defaultTheme;
}
}To summarize:
- Make sure your class implements the
ContainerFactoryPluginInterface - Declare class properties for the services you would like to inject.
- Implement the
::create()method in your class and appropriately return an instance with the injected services. - You may now access your services via your class properties.
Help improve this page
Page status: No known problems
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion