当需要许多新对象实例时,如何实现依赖注入?

时间:2013-04-03 19:35:59

标签: php dependency-injection

我正在尝试理解一些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(...);
        // ...
    }
}

这可能是在使用容器或工厂时吗?

1 个答案:

答案 0 :(得分: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的另一个对象而你只需传递一次。

相关问题