2015-12-30 83 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 
    } 

} 

通過使用工廠設計模式您不必擴展其他類 - 因爲實際上您不想擴展它們。你沒有增加新的功能,你的願望是有可測試的環境)。