I have used Dice PHP DI container for quite a while and it seems the best in terms of simplicity of injecting dependencies.
From Dice Documentation:
class A {
public $b;
public function __construct(B $b) {
$this->b = $b;
}
}
class B {
}
$dice = new DiceDice;
$a = $dice->create('A');
var_dump($a->b); //B object
However, when you have to use objects that are directly dependent on each other, the finall result is server error, because of the infinite loop.
Example:
class A {
public $b;
public function __construct(B $b) {
$this->b = $b;
}
}
class B {
public $a;
public function __construct(A $a) {
$this->a = $a;
}
}
Author of Dice says that there is no way to construct an object from the A or B classes. As:
- An 'A' object requires a 'B' object to exist before it can be created
- But a 'B' object requires an 'A' object to exist before it can be created
Author says, that this limitation concerns all DI containers!
Question:
What would be the best solution for overcoming this problem nicely without changing initial code? Could anyone provide an example of using other DI containers, when it would be possible to run exampled code without bulky workarounds?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…