Search code examples
symfonydependency-injection

How to configure a service with a class name defined on an environment variable?


I would like to load a different file/class depending on an environment variable.

I installed "symfony/expression-language" and tried this:

App\Foo\Bar\MyClass:
    class: '@=env("MY_CLASS_NAME")'

Which leads to this error message:

Invalid service "App\Foo\Bar\MyClass": class "@=env("MY_CLASS_NAME")" does not exist.

Is there any other way to load a different class depending on an env variable?


Solution

  • For the record: I don't think what you are doing is a great idea. For the scenario you describe, it would likely make more sense to use different environments, and define the service differently depending on the environment:

    services:
        App\Service\ServiceInterface:
            class: App\Service\GoodService
    
        when@aws:
            App\Service\ServiceInterface:
                class: App\Service\FooService
    
        when@test:
            App\Service\ServiceInterface:
                class: App\Service\BarService
    

    I don't really see, at the moment, a scenario where it makes sense to let an environment variable hold a class name, and not have that configuration made explicit in your config somewhere. It's not something where infinite configurability works, there is only a finite (and likely small) number of classes that can be used within the domain of your application.


    But if you still want to do this, it's much simpler that what you are trying. Simply do:

    services:
        App\Service\ServiceInterface:
            class: '%env(APP_SERVICE_CLASS)%'
    

    and then:

    #.env
    APP_SERVICE_CLASS=App\\Service\\BarService
    

    And that's it.

    (Just in case: Logically, you'll have "console clear:cache" to rebuild the container after each change in the environment variable)