我用书面(默认),如验证之前或之前删除事件触发事件。这是一个例子,为什么这样的事情是好的。
试想一下,你有一些用户。有些用户(例如管理员)可以编辑其他用户。但是你想确保遵循特定的规则(让我们看看这个: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
已经定义,顾名思义,这在删除行之前触发一个。
现在,在任何控制器,我们可以写触发这两个事件的例子:
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
}
你看过http://www.yiiframework.com/doc-2.0/guide-concept-events.html –
是这并没有帮助我。 – soju
@soju我回答了你的问题吗? :) –