Home > OS >  Symfony services.yaml env custom param condition
Symfony services.yaml env custom param condition

Time:10-29

I have a specific variable in my .env.dev.local SRV_INST=s01

Is there a way to use custom env variables in services.yaml in a conditional way similar to when@dev ? I would like to define some services only when SRV_INST=s01 (something like when %env(SRV_INST)% === 's01').

I can use services.php, but I wanted to know if there's a way to do this in services.yaml

CodePudding user response:

Okay, I solved this by importing a .php additional configuration file.

// config/services.yaml
imports:
- { resource: 'services_conditional.php' }

And the services_conditional.php file:

// config/services_conditional.php
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use SomeCustom\Service\CustomDoubleBla;

return function (ContainerConfigurator $configurator) {
    $services = $configurator->services();

    if (!empty($_ENV['SRV_INST']) && $_ENV['SRV_INST'] === 's01') {
        $services->set(CustomDoubleBla::class)
            ->decorate('custom_single_bla.service')
            // pass the old service as an argument
            ->args([service('.inner')]);
    }
};

CodePudding user response:

you found a solution - but for anyone else, there are multiple other solutions for this:

services:
    App\Mailer:
        # the '@=' prefix is required when using expressions for arguments in YAML files
        arguments: ["@=container.hasParameter('some_param') ? parameter('some_param') : 'default_value'"]

or

services:
    # ...

    App\Mail\MailerConfiguration: ~

    App\Mailer:
        # the '@=' prefix is required when using expressions for arguments in YAML files
        arguments: ['@=service("App\\Mail\\MailerConfiguration").getMailerMethod()']

you can find more information at https://symfony.com/doc/current/service_container/expression_language.html

  • Related