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(...);
// ...
}
}
难道这可能是当容器或工厂将使用?
这给了我只有一个传入类的实例。在我的例子中,我使用了几个。 – Isius 2013-04-08 17:38:07
你看到那些' - > get'方法吗? http://en.wikipedia.org/wiki/Factory_method_pattern – dynamic 2013-04-08 18:20:02
如果我正确理解这一点,MyDate类“get”方法处理日期创建,而不是一个明确的日期工厂类?我想知道'$ today = $ dateService-> get('04/08/2013');'在你的例子中更有意义。基本上是使用工厂是吗? – Isius 2013-04-08 22:25:03