依赖注入让我的代码变得丑陋

时间:2018-02-21 11:48:27

标签: php testing dependency-injection phpunit

为了测试我们使用DI,但是我遇到了问题。我想随时打电话 我的代码现在看起来很难看。我试图理解如何避免必须将所有依赖项传递给构造函数,但仍然保持可测试性。

例如,假设服务类执行护照检查

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次? 请注意,传入的三个依赖项只是新实例。

我在哪里错了?

非常感谢。

0 个答案:

没有答案