1. 程式人生 > >yii2.0依賴注入DI程式碼例項

yii2.0依賴注入DI程式碼例項

場景

使用者評論成功後可以靈活配置選用GMAIL、qq或其他郵箱傳送郵件。

檔案功能

  • EmailSenderInterface.php 郵件服務定義介面
  • GmailSender.php gmail類實現EmailSenderInterface
  • QqSender.php qq類實現EmailSenderInterface
  • Comment.php 評論類
  • DiController.php 測試演示控制器

程式碼實現

EmailSenderInterface.php

<?php
/**
 * 為郵件服務定義介面
 */

namespace backend\di\yii;
interface EmailSenderInterface
{
    public
function send(); }

GmailSender.php

<?php
/**
 * Gmail郵件服務
 */
namespace backend\di\yii;
use backend\di\yii\EmailSenderInterface;

class GmailSender implements EmailSenderInterface {
    public function send()
    {
        echo '使用gmail傳送';
    }
}

QqSender.php

<?php
/**
 * qq郵件服務
 */
namespace
backend\di\yii; use backend\di\yii\EmailSenderInterface; class QqSender implements EmailSenderInterface { public function send() { echo '使用qq傳送'; } }

Comment.php

<?php
namespace backend\di\yii;

use backend\di\yii\EmailSenderInterface;

class Comment {

    private $_eMailSender
; public function __construct(EmailSenderInterface $emailSender) { $this->_eMailSender = $emailSender; } public function sendEmail() { $this->_eMailSender->send(); } }

DiController.php

<?php

namespace backend\controllers;

use Yii;
use yii\di\Container;
class DiController extends \yii\web\Controller{

    public function actionIndex(){
        $container = new Container;
        $container->set('backend\di\yii\EmailSenderInterface',['class'=>'backend\di\yii\GmailSender']);
        $comment=$container->get('backend\di\yii\Comment');
        $comment->sendEmail();
    }

}

執行

這裡寫圖片描述
若要使用qq郵箱傳送,只需更改DiController.php更改註冊依賴關係即可:

        $container->set('backend\di\yii\EmailSenderInterface',['class'=>'backend\di\yii\QqSender']);

執行如下:
這裡寫圖片描述