2015-12-30 84 views
2

所以我已经做了一些在这里搜索,但我无法找到答案......依赖注入动态参数

我有下面的类:

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变种,这可能是(客户,联系等),所以我认为这是唯一的选择,像上面这样做。有没有办法让这个代码稍微好一点,并注入请求并使用mutator或其他设置$endpoint var?

感谢

+1

如果您只是在'Request'中添加了一个' - > getEndpoint()'方法,然后通过'Request $ request'传递了什么呢? – Will

+0

'请求'类是第三方,所以我猜测我应该真的让一个接口正确吗? –

+1

对,只需制作一个接口或适配器即可。称之为'EndpointRequest'或其他东西!你甚至可以扩展'请求'。 – Will

回答

2

我建议这样的,在那里您扩展第三方Request类的方法,并允许它接受一个getter沿$endpoint

<?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; 
    } 
} 
+0

完美,谢谢。新年快乐!!! –

1

使用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 
    } 

} 

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