简体   繁体   English

如何在symfony2捆绑软件中实施策略模式?

[英]How to implement the strategy pattern in a symfony2 bundle?

Say we have a Symfony bundle that contains a service having a dependency defined by an interface (Strategy pattern). 假设我们有一个Symfony捆绑包,其中包含一个服务,该服务的依赖项由接口定义(策略模式)。 I also have several implementations of the interface (ie. strategies) defined in the same bundle. 我也有在同一个包中定义的接口的几种实现(即策略)。 Each strategy may also have various further dependencies that my require further configuration. 每种策略可能还具有各种其他依赖性,需要进一步配置。 So my services.yml in the bundle may look like that: 因此,捆绑包中的我的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]

And I can choose the implementation in the config.yml in the application. 我可以在应用程序的config.yml中选择实现。

services:
  my_strategy:
    alias: my_strategy_service_2
  my_memcache:
    class: Memcached
    calls:
      - [ addServer, [%memcache_host%, %memcache_port%] ]

Let's stick to the example and let's change the implementation. 让我们坚持这个例子,并更改实现。 If I write in the config.yml in the application: 如果我在应用程序中写config.yml:

services:
  my_strategy:
    alias: my_strategy_service_1

it still, unfortunately requires me to define "my_memcache" service, even if it's not used this time, but only defined in the bundle. 不幸的是,即使这次没有使用它,但仅在包中定义了它,仍然需要我定义“ my_memcache”服务。 How can I deal with the situation? 我该如何处理呢? Can I enforce checking the dependencies for "my_strategy_service_2" only if it's really used? 仅当“ my_strategy_service_2”确实使用时,我可以强制检查其依赖性吗?

Usually I implement a "register" between context and strategy use: 通常,我在上下文和策略使用之间实现“注册”:

  1. Define all possibile strategies (services) and I tag them 定义所有可能的策略(服务),然后标记它们
  2. Define a register were I have injected all possibile strategies (services) by fetching them through tags (with a compiler pass ) 通过我通过标记(通过编译器传递 )获取所有可能的策略(服务)来定义寄存器
  3. Retrieve the strategy through the register (either by a configuration parameter injected or by passing it when calling the function to lookup for correct strategy) 通过寄存器检索策略(通过注入配置参数或通过在调用函数以查找正确策略时传递该参数)
  4. Use the strategy 使用策略

Hope it's clear 希望很清楚

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM