我正在寻找适用于我的问题的最佳模式。我有一个定义我的服务类功能的接口
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一起申请。我想根据客户端动态加载这些额外的步骤。
答案 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 更适合此用例。我会对您的代码进行以下更改:
resetNegotiation
方法重命名为execute
和NegotiationInterface
中的NegotiationService
。array
或list
(可以容纳NegotiationInterface
个实例)添加到NegotiationService
作为实例变量。让NegotiationService
中的构造函数请求额外的list
/ array
参数,并在构造函数中对其进行初始化。
在execute
的{{1}}方法中,遍历列表并在其中的每个NegotiationService
上调用execute
。
完成上述更改后,您可以创建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
方法。这由execute
和client
重复使用。client2
实现CallWebServiceNegotiationInterfaceImpl
并包含调用Web服务的代码
NegotiationInterface
方法。execute
实现ExportFileNegotiationInterfaceImpl
并包含导出文件的代码
NegotiationInterface
方法。