Search code examples
phpsymfonyinheritancedependency-injectioninterface

PHP Symfony - Autowiring Interface as constructor argument but using specific class from interface on test .env


Imagine we have the following Interface:

interface FooInterface {
//...
}

We have two classes that implements this interface:

class Foo implements FooInterface {
  //...
}

class Bar implements FooInterface {
  //...
}

In Symfony I want to inject the Interface and whenever I use FooInterface as DI in a constructor of a class I want the specific class "Foo". E.g.

class SomeClass {

  public function __construct(FooInterface $foo) { ... }

}

So far so good, now I want to inject the Class "Bar" only when Im on the test environement. (.env APP_ENV=test)

Is there a global config that I can use to specify which class will be injected based on the environment ?


Solution

  • Setup parameters for different envs in `config/services.yaml:

    imports:
        - { resource: 'services_' ~ env('APP_ENV') ~ '.yaml' }
    

    in config/services_prod.yaml set Foo as injected class

    Namespace\FooInterface: '@Namespace\Foo'
    

    in config/services_test.yaml set Bar as injected class

    Namespace\FooInterface: '@Namespace\Bar'