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

huangapple go评论70阅读模式
英文:

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

问题

在Symfony中,您可以使用条件参数来实现根据环境来注入特定的类。您可以在您的服务配置文件(通常是services.yaml)中设置条件参数,然后根据环境的不同来决定注入哪个类。以下是一个示例配置:

services:
    _defaults:
        autowire: true
        autoconfigure: true

    App\:
        resource: '../src/*'
        exclude: '../src/{DependencyInjection,Entity,Migrations,Tests,Kernel.php}'

    App\SomeClass:
        arguments:
            $foo: '@App\Foo' # 默认情况下注入Foo

    App\Foo:
        class: 'App\Foo'
        condition: '%env(APP_ENV)% == "test"' # 只在测试环境下注入Foo

    App\Bar:
        class: 'App\Bar'
        condition: '%env(APP_ENV)% == "test"' # 只在测试环境下注入Bar

上述示例中,我们使用condition来指定在测试环境下才会注入FooBar。这将根据.env文件中的APP_ENV环境变量来决定。如果APP_ENV是"test",则FooBar将注入到SomeClass的构造函数中;否则,将只注入Foo

请确保您的Symfony应用程序正确配置了环境变量,并且.env文件中有正确的APP_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 ?

答案1

得分: 0

设置不同环境的参数在 `config/services.yaml` 中:

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

config/services_prod.yaml 中将 Foo 设置为注入的类:

Namespace\FooInterface: '@Namespace\Foo'

config/services_test.yaml 中将 Bar 设置为注入的类:

Namespace\FooInterface: '@Namespace\Bar'

<details>
<summary>英文:</summary>

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

```php
imports:
    - { resource: &#39;services_&#39; ~ env(&#39;APP_ENV&#39;) ~ &#39;.yaml&#39; }

in config/services_prod.yaml set Foo as injected class

Namespace\FooInterface: &#39;@Namespace\Foo&#39;

in config/services_test.yaml set Bar as injected class

Namespace\FooInterface: &#39;@Namespace\Bar&#39;

huangapple
  • 本文由 发表于 2023年6月26日 17:18:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76555284.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定