Check Service Definitions in Container using Console Command in Symfony 7

Check Service Definitions in Container using Console Command in Symfony 7

Symfony framework provides static code analysis commands (also known as linters) that allows to check some parts of application such YAML syntax, TWIG syntax, etc.

This tutorial shows how to check service definitions in container using console command in Symfony 7 application.

Let's say we have the following service that has constructor with a string type parameter:

src/Service/NewsletterManager.php

<?php

namespace App\Service;

class NewsletterManager
{
    public function __construct(string $adminEmail)
    {
    }
}

Service is used in a controller:

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Service\NewsletterManager;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    public function __construct(private NewsletterManager $newsletterManager)
    {
    }

    #[Route('/')]
    public function index(): Response
    {
        return new Response();
    }
}

The lint:container command can be used to check the service definitions in the container to ensure that the service can be autowired.

php bin/console lint:container

In our case, the command prints the error that service of NewsletterManager class cannot be autowired because the constructor has a string type parameter, which should be configured explicitly.

The problem can be fixed by defining service as follows:

config/services.yaml

services:
    # ...

    App\Service\NewsletterManager:
        arguments: ['admin@example.com']

If you are using a continuous integration, recommended adding lint:container command to the list of commands which executed on each build.

Leave a Comment

Cancel reply

Your email address will not be published.