使用依赖项注入向类添加功能

时间:2017-11-03 19:55:12

标签: php oop design-patterns

我正在寻找适用于我的问题的最佳模式。我有一个定义我的服务类功能的接口

interface NegotiationInterface {
    abstract public function resetNegotiation(Negotiation $negotiantion);
} 

主类实现它

public class NegotiationService implements NegotiationInterface {

    public function __construct(…Some Dependencies…)
    {
    ….        
    }

    public function resetNegotiation(Negotiation $negotiantion){
    …. //All business logic
    }
}

NegotiationService在DI容器(基于Symfony)下注册,并通过其服务ID用于所有应用程序。

$negotiationService = $this->container->get(“negotiation_service”);
$negotiationService->resetNegotiation($negotiation);

但是我们的一些客户端(协商包含客户端信息)在调用resetNegotiation之后需要一个额外的步骤,例如我们的公共业务逻辑+调用web服务。我达到装饰模式,但我不确定它是否是使用DI时的最佳方法。如果是这样,我将如何与DI一起申请。我想根据客户端动态加载这些额外的步骤。

2 个答案:

答案 0 :(得分:1)

我必须在工作中做很多这样的课程,我们通常会使用适配器(如果我在设计模式上错了,请纠正我)。在您的情况下,您的适配器将如下所示:

public class NegotiationServiceAdapter implements NegotiationInterface {

    protected $negotiationService;

    public function __construct(NegotiationService $negotiationService)
    {
        $this->negotiationService = $negotiationService;
    }

    public function resetNegotiation(Negotiation $negotiation){
        $this->negotiationService->resetNegotiation($negotiation);

        //Rest of your custom code for that client
    }
}

请注意,我添加了" generic" NegotiationService由构造函数中的每个人使用,然后在实现的函数中,您首先(或最后,取决于您的情况)执行此实例的代码,然后执行您的自定义代码。

答案 1 :(得分:0)

  

我达到装饰模式,但我不确定它是否是使用DI

时的最佳方法

Decorator 模式相比, Composite pattern 更适合此用例。我会对您的代码进行以下更改:

  1. resetNegotiation方法重命名为executeNegotiationInterface中的NegotiationService
  2. arraylist(可以容纳NegotiationInterface个实例)添加到NegotiationService作为实例变量。
  3. NegotiationService中的构造函数请求额外的list / array参数,并在构造函数中对其进行初始化。

  4. execute的{​​{1}}方法中,遍历列表并在其中的每个NegotiationService上调用execute

  5. 完成上述更改后,您可以创建NegotiationInterface的不同实现,将其添加到NegotiationInterface / array并将其传递到list逐个遍历每个实例,并在每个实例上调用NegotiationService

    例如:

    execute

    其中:

    • $resetNegotiation = new ResetNegotiationNegotiationInterfaceImpl(); $callWebservice = new CallWebServiceNegotiationInterfaceImpl(); $negotiationInterfacesClient1 = array($resetNegotiation, $callWebservice); $negotiationServiceClient1 = new NegotiationService($dependencies, $negotiationInterfacesClient1); negotiationServiceClient1.execute($negotiation); $exportFile = new ExportFileNegotiationInterfaceImpl(); $negotiationInterfacesClient2 = array($resetNegotiation, $exportFile); $negotiationServiceClient2 = new NegotiationService($dependencies,$negotiationInterfacesClient2); negotiationServiceClient2.execute($negotiation); 实现 ResetNegotiationNegotiationInterfaceImpl并包含重置服务的代码 NegotiationInterface方法。这由executeclient重复使用。
    • client2实现CallWebServiceNegotiationInterfaceImpl并包含调用Web服务的代码 NegotiationInterface方法。
    • execute实现ExportFileNegotiationInterfaceImpl并包含导出文件的代码 NegotiationInterface方法。
相关问题