簡體   English   中英

Yii2 依賴注入示例

[英]Yii2 dependency injection example

有人可以指出我在 Yii2 中使用 DI 容器的實際示例或教程的方向嗎?

我一定很厚,但關於這個主題的 2.0 指南對我來說並不是那么清楚。 此外,我查看過的大多數在線教程和示例代碼都帶有Yii::$app單例,這使得測試變得困難。

例如你有類\\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");

現在你在調用$container->get("\\app\\components\\MyInterface");時給出 First 類的實例$container->get("\\app\\components\\MyInterface");

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

但是現在我們可以為這個接口設置其他類。

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

您可以在一處設置類,其他代碼將自動使用新類。

在這里,您可以在 Yii 中找到有關此模式的出色文檔以及代碼示例。

這是設置默認小部件設置的簡單示例:

        // 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);

我有一些類似的需求,因為生產准備就緒,我想用 Yii2 開始新項目,但最終我會在 yii3 准備好生產后轉移到它。 為了保持遷移容易,建議從 yii 用依賴注入替換 Yii::$app ,這就是我需要為要在控制器中使用的組件實現依賴注入的地方。

這是我的組件。

<?php

namespace common\services;

use Yii;
use yii\base\Component;

class HelloService extends Component
{
    public function welcome() {
        echo "Welcome from service component";
    }
}

這是我的控制器使用上述組件並通過依賴注入訪問它。

<?php
namespace console\controllers;

use yii\console\Controller;
use common\services\HelloService;

class HelloController extends Controller
{
    public $message;
    /** @var common\services\HelloService $helloService */
    private $helloService;

    public function __construct($id, $module, HelloService $helloService, $config = [])
    {
        $this->helloService = $helloService;
        parent::__construct($id, $module, $config);
    }
    
    public function actionIndex()
    {
        echo $this->helloService->welcome() . "\n";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM