具有动态参数的依赖项注入


Dependency injection with dynamic parameter

所以我在这里做了一些搜索,但找不到答案。。。

我有以下课程:

class SomeCrmService
{
    public function __construct($endpoint, $key)
    {
        $this->request = new Request($endpoint);
        $this->request->setOption(CURLOPT_USERPWD, $key);
        $this->request->setOption(CURLOPT_HTTPHEADER, array(
            "Content-type : application/json;", 'Accept : application/json'
        ));
        $this->request->setOption(CURLOPT_TIMEOUT, 120);
        $this->request->setOption(CURLOPT_SSL_VERIFYPEER, 0);
    }

我遇到的问题是,我想注入Request,这样我就可以更改我正在使用的库,并且在测试时更容易模拟。我需要传入$endpoint变量,它可以是(客户、联系人等),所以我认为这是像上面这样做的唯一选项。有没有一种方法可以让这个代码稍微好一点,注入Request并使用mutator或其他东西来设置$endpoint var?

感谢

我推荐这样一种方法,扩展第三方Request类,并允许它接受$endpoint和getter:

<?php
class EndpointRequest extends Request
{
    protected $endpoint;
    public function __construct($endpoint, $key)
    {
        $this->setOption(CURLOPT_USERPWD, $key);
        $this->setOption(CURLOPT_HTTPHEADER, array(
            "Content-type : application/json;", 'Accept : application/json'
        ));
        $this->setOption(CURLOPT_TIMEOUT, 120);
        $this->setOption(CURLOPT_SSL_VERIFYPEER, 0);
    }
    public function getEndpoint()
    {
        return $this->endpoint;
    }
}
class SomeCrmService
{
    public function __construct(EndpointRequest $request)
    {
        $this->request = $request;
    }
}

使用Factory设计模式:

<?php
class RequestFactory {
    public function create($endpoint) {
        return new Request($endpoint);
    }
}
class SomeCrmService
{
    public function __construct($endpoint, $key, RequestFactory $requestFactory)
    {
        // original solution
        // $this->request = new Request($endpoint);
        // better solution
        $this->request = $requestFactory->create($endpoint);
        // here comes the rest of your code
    }
}

通过使用工厂设计模式,您不必扩展其他类,因为实际上您不想扩展它们。您不是在添加新功能,您的愿望是拥有可测试的环境)。