yamlsymfony5

How to autowire 2 symfony services, which use the same interface and addtional arguments


I have two services, which both use the same interface and one is injected in the other. With this configuration in the service.yaml everything worked well:

    # fix autowiring for 2 services using the same interface
    App\Domain\ListService: ~
    App\Domain\SapService\SapListService: ~
    
    App\Domain\ListService $sapListService: '@App\Domain\SapService\SapListService'
    App\Domain\ListServiceInterface: '@App\Domain\ListService'

following the official documentation found here.

Now one of my services needs the information in which environment the class is currently running.

In a simple service configuration I would write it like this:

    App\Service\FooService:
        arguments:
            $env: '%env(APP_ENV)%'

But how do I add the environment information in my more complex situation?

I tried this:

    App\Domain\ListService: ~
    App\Domain\SapService\SapListService: ~

    App\Domain\ListService $sapListService: '@App\Domain\SapService\SapListService'
        arguments:
            $env: '%env(APP_ENV)%'
    App\Domain\ListServiceInterface: '@App\Domain\ListService'

which throws this error:

The file "/var/www/src/../config/services.yaml" does not contain valid YAML: Unable to parse at line 52 (near "    arguments:").

What is the proper formatting to parse the environment information into my service?

I tried manual wiring like this:

    public function __construct(
        ListServiceInterface $sapListService,
        #[Autowire('%env(APP_ENV)%')]
        string $env
    ) {
        $this->sapListService = $sapListService;
        $this->env = $env;
    }

which gives me the error:

In DefinitionErrorExceptionPass.php line 54:

  Cannot autowire service "App\Domain\ListService": argument "$env" of method "__construct()" is type-hinted "string", you should configure its
   value explicitly.

Looks like the Autowire annotation is only available with symfony 6


Solution

  • You should use the namespace in the redis config to separate the different environments and not use the APP_ENV var to create the keys to store.