2017-01-07 31 views
4

努力学习Yii中2赛事澄清我发现了一些资源。我得到更多关注的链接在这里。需要在活动YII2

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的一部分。请用一个例子来解释。提前致谢。

+0

你看过http://www.yiiframework.com/doc-2.0/guide-concept-events.html –

+0

是这并没有帮助我。 – soju

+0

@soju我回答了你的问题吗? :) –

回答

8

我用书面(默认),如验证之前或之前删除事件触发事件。这是一个例子,为什么这样的事情是好的。

试想一下,你有一些用户。有些用户(例如管理员)可以编辑其他用户。但是你想确保遵循特定的规则(让我们看看这个: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 
} 
+0

很好的例子。谢谢你edvin。 – soju