如何在 yii2 中使用事件?
我已经浏览了使用Google找到的文档和所有文章。有人能给我一个很好的例子,说明如何在 Yii2 中使用事件,以及它在哪里看起来合乎逻辑?Yii2 events
我已经浏览了使用Google找到的文档和所有文章。有人能给我一个很好的例子,说明如何在 Yii2 中使用事件,以及它在哪里看起来合乎逻辑?Yii2 events
我可以通过一个简单的例子来解释事件。比方说,当用户首次注册到网站时,您希望做一些事情,例如:
您可以尝试在成功保存用户对象后调用几个方法。也许像这样:
if($model->save()){
$mailObj->sendNewUserMail($model);
$notification->setNotification($model);
}
到目前为止,这似乎很好,但是如果需求数量随着时间的推移而增长怎么办?说用户注册后必须发生10件事?在这种情况下,事件会派上用场。
事件基础知识
事件由以下循环组成。
User
const EVENT_NEW_USER='new_user';
$event
model
on()
trigger()
请注意,上面提到的所有方法都是类的一部分。Yii2 中几乎所有的类都继承了这个类。是的。Component
ActiveRecord
让我们编写代码
为了解决上面提到的问题,我们可以有模型。我不会在这里编写所有代码。User.php
// in User.php i've declared constant that stores event name
const EVENT_NEW_USER = 'new-user';
// say, whenever new user registers, below method will send an email.
public function sendMail($event){
echo 'mail sent to admin';
// you code
}
// one more hanlder.
public function notification($event){
echo 'notification created';
}
这里要记住的一件事是,您不必在创建事件的类中创建方法。您可以从任何类中添加任何静态、非静态方法。
我需要将上述处理程序附加到事件。我做的基本方法是使用AR的方法。所以这是如何:init()
// this should be inside User.php class.
public function init(){
$this->on(self::EVENT_NEW_USER, [$this, 'sendMail']);
$this->on(self::EVENT_NEW_USER, [$this, 'notification']);
// first parameter is the name of the event and second is the handler.
// For handlers I use methods sendMail and notification
// from $this class.
parent::init(); // DON'T Forget to call the parent method.
}
最后一件事是触发一个事件。现在,您不需要像以前那样显式调用所有必需的方法。您可以通过以下方式替换它:
if($model->save()){
$model->trigger(User::EVENT_NEW_USER);
}
将自动调用所有处理程序。
对于“全球”事件。
(可选)您可以创建专用事件类
namespace your\handler\Event\Namespace;
class EventUser extends Event {
const EVENT_NEW_USER = 'new-user';
}
定义至少一个处理程序类:
namespace your\handler\Event\Namespace;
class handlerClass{
// public AND static
public static function handleNewUser(EventUser $event)
{
// $event->user contain the "input" object
echo 'mail sent to admin for'. $event->user->username;
}
}
在配置的组件部分内(在本例中为)用户组件插入 you 事件:
'components' => [
'user' => [
...
'on new-user' => ['your\handler\Event\Namespace\handlerClass', 'handleNewUser'],
],
...
]
然后在代码中,您可以触发事件:
Yii::$app->user->trigger(EventUser::EVENT_NEW_USER, new EventUser($user));
加
您还可以使用闭包:
例:
'components' => [
'user' => [
...
'on new-user' => function($param){ your\handler\Event\Namespace\handlerClass::handleNewUser($param);},
'on increment' => function($param){ \Yii::$app->count += $param->value;},
],
...
]