Yii創建事件

在本章中,我們將學習在Yii中創建事件。要顯示操作事件,需要準備一些原始數據。

準備資料庫

第1步 - 創建一個新的資料庫。資料庫可以通過以下兩種方式進行。
  • 在終端運行 mysql -u root –p

  • 登錄數據後,通過執行 CREATE DATABASE mystudy CHARACTER SET utf8 COLLATE utf8_general_ci; 創建一個新的資料庫;

第2步 - 在 config/db.php 檔中配置資料庫連接。下麵的配置可根據自己的實際情況配置。
<?php
   return [
      'class' => 'yii\db\Connection',
      'dsn' => 'mysql:host = localhost;dbname = mystudy',
      'username' => 'root',
      'password' => '',
      'charset' => 'utf8',
   ];
?>

第3步 - 在專案根檔夾執行:yii migrate/create test_table 。此命令將用於創建管理資料庫資料庫遷移。 migrations檔會出現在專案的根的 migrations 檔夾中。
Yii數據Widgets

第4步 - 修改遷移檔(在本示例中生成的是:m160529_014611_test_table.php),並使用以下這些代碼。
<?php
   use yii\db\Schema;
   use yii\db\Migration;
   class m160529_014611_test_table extends Migration {
      public function up() {
         $this->createTable("user", [
            "id" => Schema::TYPE_PK,
            "name" => Schema::TYPE_STRING,
            "email" => Schema::TYPE_STRING,
         ]);
         $this->batchInsert("user", ["name", "email"], [
            ["User1", "user11@gmail.com"],
            ["User2", "user22@gmail.com"],
            ["User3", "user33@gmail.com"],
            ["User4", "user44@gmail.com"],
            ["User5", "user55@gmail.com"],
            ["User6", "user66@gmail.com"],
            ["User7", "user77@gmail.com"],
            ["User8", "user88@gmail.com"],
            ["User9", "user99@gmail.com"],
            ["User10", "user1010@gmail.com"],
            ["User11", "user1111@gmail.com"],
         ]);
      }
      public function down() {
         //$this->dropTable('user');
      }
   }
?>
上述遷移創建用戶表,它包含了以下這些字段:id, name, 和 email。它還增加了一些演示用戶帳號。
第5步 - 在專案的根目錄內運行: yii migrate  來遷移應用到資料庫。執行結果如下圖所示:

第6步-現在,我們需要為user表創建模型。為了簡便起見,我們將使用GII代碼生成工具。在流覽器中打開 url: http://localhost:8080/index.php?r=gii 。
然後,點擊 “Model generator” 下的 “Start”按鈕。 填寫表名(“user”)和模型類(“MyUser”),單擊“Preview”按鈕,最後點擊 “Generate” 按鈕。



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);
   }
}
第3步 - 現在訪問:http://localhost:8080/index.php?r=site/test-event ,會看到以下輸出結果:
Yii創建事件

上一篇: Yii事件 下一篇: Yii行為