Yii2依赖注入示例

Pap*_*Dee 6 php dependency-injection yii2

有人能指出我在Yii2中使用DI容器的实际示例或教程的方向吗?

我一定很厚,但关于这个问题的2.0指南对我来说并不是那么清楚.此外,我所评论的大多数在线教程和示例代码都充斥着Yii::$app单例,这使得测试变得困难.

Har*_*ari 5

例如,您有类\app\components\First\app\components\Second实现了一个接口\app\components\MyInterface

您只能在一处使用 DI 容器来更改类。例如:

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");
Run Code Online (Sandbox Code Playgroud)

现在你在调用时给出 First 类的实例 $container->get("\app\components\MyInterface");

$obj = $container->get("\app\components\MyInterface");
$obj->test(); // print "First  class"
Run Code Online (Sandbox Code Playgroud)

但是现在我们可以为这个接口设置其他类。

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

您可以在一处设置类,其他代码将自动使用新类。

在这里,您可以在 Yii 中找到有关此模式的出色文档以及代码示例。