Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 dependency injection example

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.

like image 628
Papa Joe Dee Avatar asked Apr 23 '15 22:04

Papa Joe Dee


1 Answers

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.

like image 136
Haru Atari Avatar answered Oct 12 '22 13:10

Haru Atari