Yii2 dependency injection example

Can someone point me towards a practical example or tutorial using the DI container in Yii2?

I have to be fat, but I just don’t understand the 2.0 guide on this topic. In addition, most of the online tutorials and code examples that I reviewed are plastered with the Yii::$app singleton, which makes testing difficult.

+6
source share
2 answers

For example, you have classes \app\components\First and \app\components\Second implements one interface \app\components\MyInterface

You can use the DI container to change the class in only one place. For instance:

 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 specify an instance of the 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 another class for this class.

 $container->set ("\app\components\MyInterface","\app\components\Second"); $obj = $container->get("\app\components\MyInterface"); $obj->test(); // print "Second class" 

You can set the classes in one place and the other automatically use the new class.

Here you can find great documentation for this template in Yii with code examples.

+4
source

This is a simple example for setting default widget settings:

  // Gridview default settings $gridviewSettings = [ 'export' => false, 'responsive' => true, 'floatHeader' => true, 'floatHeaderOptions' => ['scrollingTop' => 88], 'hover' => true, 'pjax' => true, 'pjaxSettings' => [ 'options' => [ 'id' => 'grid-pjax', ], ], 'resizableColumns' => false, ]; Yii::$container->set('kartik\grid\GridView', $gridviewSettings); 
+2
source

Source: https://habr.com/ru/post/985826/


All Articles