2013-04-03 49 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