Autowire services with the Autowire attribute in Drupal
If dependencies are injected into a service class, changes must be made in both the `*.services.yml` file and the PHP class itself.
<?php
declare(strict_types=1);
namespace Drupal\my_module;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
class Example {
public function __construct(
#[Autowire(service: 'current_user')]
private readonly AccountInterface $currentUser,
) {
}
public function getCurrentUser(): AccountInterface {
return $this->currentUser;
}
}
services:
my_module.example:
class: Drupal\my_module\Service\Example
autowire: true
Drupal\my_module\Service\Example: '@my_module.example'
Issue:
If dependencies are injected into a service class, changes must be made in both the `*.services.yml` file and the PHP class itself.
Solution:
If we set autowiring to true in the *.services.yml file, we can use the Autowire attribute in our PHP service class. This allows us to focus on the service class itself without having to switch between the *.services.yml file and the PHP service class.
Ihre Drupal-Website zukunftssicher machen
Wir prüfen Ihr System und zeigen, was Sie für AI, Wartung und Upgrades brauchen.