Can someone point me in the direction of a practical example or tutorial using the DI container in Yii2?
I must be thick but the 2.0 guide on this subject is just not that clear to me. Also, most on-line tutorial and sample code I have reviewed is peppered with the Yii::$app
singleton, which makes testing difficult.
For example you have classes \app\components\First
and \app\components\Second
implements one interface \app\components\MyInterface
You can use DI container to change class only in one place. For example:
class First implements MyInterface{
public function test()
{
echo "First class";
}
}
class Second implements MyInterface {
public function test()
{
echo "Second class";
}
}
$container= new \yii\di\Container();
$container->set ("\app\components\MyInterface","\app\components\First");
Now you give instance of First class when calling $container->get("\app\components\MyInterface");
$obj = $container->get("\app\components\MyInterface");
$obj->test(); // print "First class"
But now we can set other class for this interface.
$container->set ("\app\components\MyInterface","\app\components\Second");
$obj = $container->get("\app\components\MyInterface");
$obj->test(); // print "Second class"
You can set classes in one place and other code will used new class automatically.
Here you can find great documentation for this pattern in Yii with code examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With