php - 需要对事件 YII2 进行更多澄清

标签 php yii2

尝试学习 Yii 2 中的事件。我找到了一些资源。我比较关注的链接在这里。

How to use events in yii2?

在第一条评论中,他用一个例子进行了解释。举例来说,注册后我们有 10 件事要做 - 在这种情况下,事件会派上用场。

调用该函数有什么大不了的?模型 init 方法内部也发生同样的事情:

$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);

我的问题是使用事件有什么意义?我应该如何充分利用它们?请注意,这个问题纯粹是学习 Yii 2 的一部分。请举例说明。提前致谢。

最佳答案

我将触发事件用于写入(默认)事件,例如验证之前或删除之前。这是一个为什么这样的东西很好的例子。

假设您有一些用户。某些用户(例如管理员)可以编辑其他用户。但您想确保遵循特定规则(让我们看一下: Only main administrator can create new users and main administrator cannot be deleted )。那么你能做的就是使用这些写入的默认事件。

User模型(假设User模型拥有所有用户)你可以写init()以及您在 init() 中定义的所有其他方法:

public function init()
{
    $this->on(self::EVENT_BEFORE_DELETE, [$this, 'deletionProcess']);
    $this->on(self::EVENT_BEFORE_INSERT, [$this, 'insertionProcess']);
    parent::init();
}

public function deletionProcess()
{
    // Operations that are handled before deleting user, for example:
    if ($this->id == 1) {
        throw new HttpException('You cannot delete main administrator!');
    }
}

public function insertionProcess()
{
    // Operations that are handled before inserting new row, for example:
    if (Yii::$app->user->identity->id != 1) {
        throw new HttpException('Only the main administrator can create new users!');
    }
}

常量如self::EVENT_BEFORE_DELETE已经定义了,顾名思义,这个是在删除一行之前触发的。

现在,在任何 Controller 中,我们可以编写一个触发这两个事件的示例:

public function actionIndex()
{
    $model = new User();
    $model->scenario = User::SCENARIO_INSERT;
    $model->name = "Paul";
    $model->save(); // `EVENT_BEFORE_INSERT` will be triggered

    $model2 = User::findOne(2);
    $model2->delete(); // `EVENT_BEFORE_DELETE` will be trigerred
    // Something else
}

关于php - 需要对事件 YII2 进行更多澄清,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41519116/

相关文章:

php - 搜索在 yii2 中不起作用

mysql - yii2 : Cannot Show Data in Widget GridView

javascript - 客户端(JS-Browser)和服务器(PHP)通过 Web-Socket 通过 IP 进行通信

php - CodeIgniter 具有多种功能的交易

php - 查找最大的连续时间段集

yii2 - 将 yii2 RBAC 与规则类一起使用时,如何控制 yii2 GridView 的 ActionColumn 中按钮的可见性?

php - 如何在 yii2 中动态加载内容中加载小部件?

php - 无法联系 ldap_bind($con, $rdn, $pwd) 上的 LDAP 服务器

php - While 循环和多个条件

php - 如何在php中将形状文件x,y坐标转换为经纬度