尝试学习 Yii 2 中的事件。我找到了一些资源。我比较关注的链接在这里。
在第一条评论中,他用一个例子进行了解释。举例来说,注册后我们有 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/