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.
source share