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 migration/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 migration 以将迁移应用于数据库。
步骤 6 − 现在,我们需要为我们的 user 表创建一个模型。为简单起见,我们将使用 Gii 代码生成工具。打开此 url:http://localhost:8080/index.php?r=gii。然后,单击"模型生成器"标题下的"开始"按钮。填写表名("user")和模型类("MyUser"),单击"预览"按钮,最后单击"生成"按钮。
MyUser 模型应出现在模型目录中。
创建事件
假设我们想在新用户在我们的网站上注册时向管理员发送电子邮件。
步骤 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 − 现在输入 http://localhost:8080/index.php?r=site/test-event,您将看到以下内容。