【发布时间】:2018-08-01 16:23:43
【问题描述】:
我想创建一组依赖项,而不是到处注入它们。工厂模式会支持这个想法吗?还是有另一种处理方式?
例如:
class PassportCheckFactory {
protected $clientInstance;
protected $responseInstance;
public function buildDependancies() : bool
{
$this->clientInstance = new PassportCheckSoapClient;
$this->responseInstance = new PassportCheckResponse;
return true;
}
public function getResponseInstance()
{
return $this->responseInstance;
}
public function getClientInstance()
{
return $this->clientInstance;
}
}
这会创建并保存我们将使用的类,因此我们不需要注入它们。
例如,我们可以这样做
$request = new WhateverRequestClass;
$factory = (new PassportCheckFactory)->buildDependancies();
$service = new PassportCheckService($request, $factory);
$response = $service->execute();
代替:
$request = new WhateverRequestClass;
$service = new PassportCheckService($request, new PassportCheckSoapClient, new PassportCheckResponse);
$response = $service->execute();
【问题讨论】:
-
我建议使用最后一个示例("instead of"),因为这是正确的依赖注入。它也将更容易测试(传递模拟对象等)。在您的其他示例中,您基本上已经将您的工厂类变成了服务定位器。您的工厂还将实例化所有类,无论您是否需要它们来完成该请求。
-
我还建议您研究一些 IoC 容器,这些容器可以使您的代码更清晰、更易于管理,例如 Pimple、Illuminate\Container 或类似容器。这是一篇关于依赖注入和容器的 stackoverflow 帖子:stackoverflow.com/questions/18562752/…
-
感谢@MagnusEriksson 如果我使用 IoC 容器,是否会将我的代码与该容器代码紧密耦合。假设我需要在遗留代码库中使用该功能,而要求不支持容器,我会被卡住吗?
标签: php unit-testing design-patterns phpunit tdd