【发布时间】:2017-07-29 07:25:04
【问题描述】:
假设我们有一个 Symfony 包,其中包含一个服务,该服务具有由接口定义的依赖项(策略模式)。我还在同一个包中定义了几个接口的实现(即策略)。每个策略还可能有各种进一步的依赖项,我需要进一步配置。所以我在 bundle 中的 services.yml 可能看起来像这样:
services:
my_service:
class: MyBundle\Services\MyService
arguments: ['@my_strategy']
my_strategy_service_1:
class: MyBundle\Services\MyStrategyService1
my_strategy_service_2:
class: MyBundle\Services\MyStrategyService2
argument: [@my_memcache]
而且我可以在应用程序的config.yml中选择实现。
services:
my_strategy:
alias: my_strategy_service_2
my_memcache:
class: Memcached
calls:
- [ addServer, [%memcache_host%, %memcache_port%] ]
让我们坚持这个例子,让我们改变实现。如果我在应用程序的 config.yml 中写:
services:
my_strategy:
alias: my_strategy_service_1
不幸的是,它仍然需要我定义“my_memcache”服务,即使这次没有使用它,但只在捆绑包中定义。我该如何处理这种情况?我可以强制检查“my_strategy_service_2”的依赖关系,除非它真的被使用了吗?
【问题讨论】:
-
DIC 无法知道
my_strategy_service_2将来是否会被使用。这是只有你知道的事情。如果您不使用my_strategy_service_2,只需将其从 DIC 配置中删除即可。
标签: php symfony dependency-injection