我想了解如何使用DI容器。在PHP中手動創建/使用DI容器?
比方說,我有三類:A,B,和C像這樣定義的:
class A {}
class B
{
private $a;
public function set_a(A $a)
{
$this->a = $a;
}
}
class C
{
private $b;
public function set_b(B $b)
{
$this->b = $b;
}
}
現在我真的不明白,就是我應該在index.php來寫。我讀過實例化一個Container並不是一件好事,然後將它傳遞給我的對象,以便它們可以使用它,因爲它使我的對象依賴於容器。但這是否意味着,我必須在index.php中寫這樣的內容:
$container = new Container();
$container->a = function($ctnr) {
return new A();
}
$container->b = function($ctnr) {
$b = new B();
$b->set_a($ctnr->a);
return $b;
}
$container->b = function($ctnr) {
$c = new C();
$c->set_b($ctnr->b);
return $c;
}
$c = $container->c;
這是要走的路嗎?