Dependency injection in Symfony: services and autowiring

Dependency injection in Symfony: the container creates the services and, through autowiring, passes them to the classes that ask for them in their constructor.

class Cuisine
{
    public function __construct(private readonly PlatRepository $plats)
    {
    }

    public function platDuJour(): ?Plat
    {
        return $this->plats->findOneBy(['specialite' => true], ['id' => 'ASC']);
    }
}

class MenuController extends AbstractController
{
    public function __construct(private readonly Cuisine $cuisine)
    {
    }
}

Every class in src/ becomes a service with no configuration: typing a constructor argument is enough for the container to provide the instance, the same one for the whole request. A class no longer creates its dependencies, it receives them; business logic leaves the controller, and you can change the data source without touching the code that uses it. Controller actions can also receive a service as an argument (Cuisine $cuisine), which other services can't. debug:autowiring lists the available types. The trap: autowiring resolves classes and interfaces, not values. A string $cle argument in a constructor makes the container fail to build until you give it its value, for instance with #[Autowire('%env(CLE)%')].

The exercises have you move the list of dishes out of the controller into a Cuisine (kitchen) service, injected into the menu and home page controllers, then inject the PlatRepository into that service so it reads the menu from the database, without changing a single line of the controllers.

2 exercises work on this concept, by writing code in the browser.

In the tracks

Related concepts

Console command