Dependency Injection in Drupal
Overview:
Dependency Injection (DI) is a design pattern used in Drupal to provide objects with their
dependencies rather than creating them internally.
This approach makes the code more testable, decoupled, and easier to maintain.
Key Concepts:
1. Services:
- Services are reusable PHP objects defined in the service container.
- Common services include database connections, mail manager, logger, etc.
2. Service Container:
- Manages service instantiation and dependency resolution.
- Defined in YAML files like [Link].
Using Dependency Injection:
1. Define Dependencies in Services:
Example: Define a service in your_module.[Link]
your_module.example_service:
class: Drupal\your_module\ExampleService
arguments: ['@[Link]']
2. Inject Services into a Class via Constructor:
class ExampleService {
protected $loggerFactory;
public function __construct(LoggerFactoryInterface $logger_factory) {
$this->loggerFactory = $logger_factory;
3. Controller Example:
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Controller\ControllerBase;
class ExampleController extends ControllerBase {
protected $logger;
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
public static function create(ContainerInterface $container) {
return new static($container->get('[Link]'));
}
public function content() {
$this->logger->info('Dependency Injection example');
return ['#markup' => 'Hello from DI'];
Best Practices:
- Always inject services via the constructor.
- Avoid using \Drupal::service() except in procedural code.
- Use interfaces for type hinting to ensure flexibility.
Conclusion:
Dependency Injection is a powerful tool in Drupal that helps build clean, maintainable, and testable
code.
Understanding and applying DI properly is essential for modern Drupal development.