对于可测试性,我们使用DI,但我有一个问题。任何时候我想打电话
我的代码现在看起来很难看。我试图理解如何避免将所有依赖项传递给构造函数,同时仍保持可测试性。
例如,让我们设想一个服务类来执行passport检查
Person < holds person data
PassportCheckService < enables us to perform check
PassportCheckRequest < holds params and any logic such as validation
PassportCheckSoapClient < php soap client with options specific to request
PassportCheckResponse < the response object
PersonDocumentService < save documents for a person
班级
class PassportCheckService {
protected $person;
protected $request;
protected $response;
protected $client;
protected $personDocumentService;
// constructor
public function __construct(
Person $person,
PassportCheckRequest $request,
PassportCheckResponse $response,
PassportCheckSoapClient $client,
PersonDocumentService $personDocumentService
) {
$this->person = $person;
$this->request = $request;
$this->response = $response;
$this->client = $client;
$this->personDocumentService = $personDocumentService;
}
// perform service
public function execute() : PassportCheckResponse
{
// make call & build response instance
$this->response->build($this->client->performCall($this->request));
// save document
if ($this->response->isSuccessStatus() &&
$this->response->hasSavableDocument()
) {
$this->personDocumentService->saveDocument(
$this->person,
$this->response->getDocumentFilename(),
$this->response->getDocumentContents(),
$this->response->getDocumentMime()
);
}
// return response
return $this->response;
}
}
问题是为了调用此服务,我必须通过依赖项:
$passportCheckService = new PassportCheckService(
$person,
$request,
new PassportCheckResponse,
new PassportCheckSoapClient,
new PersonDocumentService
);
$passportCheckResponse = $passportCheckService->execute();
想象一下,服务中又添加了5个操作,现在我们需要再注入5个?
请注意,传入的依赖项中有三个只是新实例。
我哪里做错了?
非常感谢。