13.11.2025 | Peter Majmesku

Autowire services with the Autowire attribute in Drupal

Example.php
<?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;
  }

}

my_module.services.yml
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.