2013-04-03 246 views
1

我想了解一些DI概念。像這個例子一樣,可以很容易地爲每個依賴項轉換單個實例。當需要多個新對象實例時,如何實現依賴注入?

非DI

$my_cal = new MyCal(); 

class MyCal { 
    public function __construct() { 
     $this->date = new MyDate(); 
     $this->label = new MyLabel(); 
    } 
} 

DI

$my_date = new MyDate(); 
$my_label = new MyLabel(); 
$my_cal = new MyCal($my_date, $my_label); 

class MyCal { 
    public function __construct(MyDate $date_class, MyLabel $label_class) { 
     $this->date = $date_class; 
     $this->label = $label_class; 
    } 
} 

卻怎麼也有許多實例類調用(比如30,例如)被轉換?

非DI

$my_cal = new MyCal(); 

class MyCal { 
    public function __construct() { 
     $today  = new MyDate(...); 
     $tomorrow = new MyDate(...); 
     $next_day = new MyDate(...); 
     $yesterday = new MyDate(...); 
     $another_day = new MyDate(...); 
     // ... 
     $label1 = new MyLabel(...); 
     $label2 = new MyLabel(...); 
     $label3 = new MyLabel(...); 
     $label4 = new MyLabel(...); 
     // ... 
    } 
} 

難道這可能是當容器或工廠將使用?

回答

0

該解決方案非常簡單。
您只需要傳遞ONCE的依賴關係。在這種情況下,你應該做這樣的事情:

$date = new MyDate(); 

class MyCal { 
    function __construct(MyDate $dateService) { 
     $today  = $dateService->get('today'); 
     $tomorrow = $dateService->get('tomorrow'); 
     $next_day = $dateService->get('next_day'); 
     ... 
    } 
} 

通過這一點,你是暴露你的類取決於MyDate另一個對象,你只需通過一次的事實。

+0

這給了我只有一個傳入類的實例。在我的例子中,我使用了幾個。 – Isius 2013-04-08 17:38:07

+0

你看到那些' - > get'方法嗎? http://en.wikipedia.org/wiki/Factory_method_pattern – dynamic 2013-04-08 18:20:02

+0

如果我正確理解這一點,MyDate類「get」方法處理日期創建,而不是一個明確的日期工廠類?我想知道'$ today = $ dateService-> get('04/08/2013');'在你的例子中更有意義。基本上是使用工廠是嗎? – Isius 2013-04-08 22:25:03

相關問題