我正在尝试理解一些 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 个)的类?
非直接投资
$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(...);
// ...
}
}
这可能是使用容器或工厂的时候吗?