Yii - 建立事件



本章將介紹如何在 Yii 中建立事件。為了演示事件的實際應用,我們需要一些資料。

準備資料庫

步驟 1 - 建立一個新的資料庫。資料庫可以透過以下兩種方式建立。

  • 在終端執行 mysql -u root –p

  • 使用 CREATE DATABASE helloworld CHARACTER SET utf8 COLLATE utf8_general_ci; 建立一個新的資料庫。

步驟 2 - 在 config/db.php 檔案中配置資料庫連線。以下配置適用於當前使用的系統。

<?php
   return [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host=localhost;dbname=helloworld',
      'username' => 'vladimir',
      'password' => '12345',
      'charset' => 'utf8',
   ];
?>

步驟 3 - 在根資料夾內執行 ./yii migrate/create test_table。此命令將建立一個數據庫遷移檔案來管理我們的資料庫。遷移檔案應該出現在專案根目錄的 migrations 資料夾中。

步驟 4 - 修改遷移檔案(在本例中為 m160106_163154_test_table.php)。

<?php
   use yii\db\Schema;
   use yii\db\Migration;
   class m160106_163154_test_table extends Migration {
      public function safeUp() {
         $this->createTable("user", [
            "id" => Schema::TYPE_PK,
            "name" => Schema::TYPE_STRING,
            "email" => Schema::TYPE_STRING,
         ]);
         $this->batchInsert("user", ["name", "email"], [
            ["User1", "user1@gmail.com"],
            ["User2", "user2@gmail.com"],
            ["User3", "user3@gmail.com"],
            ["User4", "user4@gmail.com"],
            ["User5", "user5@gmail.com"],
            ["User6", "user6@gmail.com"],
            ["User7", "user7@gmail.com"],
            ["User8", "user8@gmail.com"],
            ["User9", "user9@gmail.com"],
            ["User10", "user10@gmail.com"],
            ["User11", "user11@gmail.com"],
         ]);
      }
      public function safeDown() {
         $this->dropTable('user');
      }
   }
?>

上述遷移建立了一個名為 user 的表,包含 id、name 和 email 欄位。它還添加了一些演示使用者。

步驟 5 - 在專案根目錄內執行 ./yii migrate 將遷移應用到資料庫。

步驟 6 - 現在,我們需要為我們的 user 表建立一個模型。為簡便起見,我們將使用 Gii 程式碼生成工具。開啟此 url: https://:8080/index.php?r=gii。然後,點選“Model generator”下的“Start”按鈕。填寫表名(“user”)和模型類名(“MyUser”),點選“Preview”按鈕,最後點選“Generate”按鈕。

Creating Event Preparing DB

MyUser 模型應該出現在 models 目錄中。

建立事件

假設我們希望每當有新使用者註冊到我們的網站時,向管理員傳送一封電子郵件。

步驟 1 - 修改 models/MyUser.php 檔案。

<?php
   namespace app\models;
   use Yii;
   /**
   * This is the model class for table "user".
   *
   * @property integer $id
   * @property string $name
   * @property string $email
   */
   class MyUser extends \yii\db\ActiveRecord {
      const EVENT_NEW_USER = 'new-user';
      public function init() {
         // first parameter is the name of the event and second is the handler.
         $this->on(self::EVENT_NEW_USER, [$this, 'sendMailToAdmin']);
      }
      /**
      * @inheritdoc
      */
      public static function tableName() {
         return 'user';
      }
      /**
      * @inheritdoc
      */
      public function rules() {
         return [
            [['name', 'email'], 'string', 'max' => 255]
         ];
      }
      /**
      * @inheritdoc
      */
      public function attributeLabels() {
         return [
            'id' => 'ID',
            'name' => 'Name',
            'email' => 'Email',
         ];
      }
      public function sendMailToAdmin($event) {
         echo 'mail sent to admin using the event';
      }
   }
?>

在上面的程式碼中,我們定義了一個“new-user”事件。然後,在 init() 方法中,我們將 sendMailToAdmin 函式附加到“new-user”事件。現在,我們需要觸發此事件。

步驟 2 - 在 SiteController 中建立一個名為 actionTestEvent 的方法。

public function actionTestEvent() {
   $model = new MyUser();
   $model->name = "John";
   $model->email = "john@gmail.com";
   if($model->save()) {
      $model->trigger(MyUser::EVENT_NEW_USER);
   }
}

在上面的程式碼中,我們建立了一個新使用者並觸發了“new-user”事件。

步驟 3 - 現在輸入 https://:8080/index.php?r=site/test-event,您將看到以下內容。

Creating Event
廣告