如何在Laravel 5.1中将模型事件添加到事件订阅者类中


How to add model events to an event subscriber class in Laravel 5.1

我想重构一些事件,所以我创建了一个事件订阅者类。

class UserEventListener
{
    public function onUserLogin($event, $remember) {
        $event->user->last_login_at = Carbon::now();
        $event->user->save();
    }
    public function onUserCreating($event) {
         $event->user->token = str_random(30);
    }
    public function subscribe($events)
    {
      $events->listen(
        'auth.login',
        'App'Listeners'UserEventListener@onUserLogin'
       );
      $events->listen(
        'user.creating',
        'App'Listeners'UserEventListener@onUserCreating'
       );
    }
}

我注册侦听器如下:

 protected $subscribe = [
    'App'Listeners'UserEventListener',
];

我在用户模型的引导方法中添加了以下内容:

public static function boot()
{
    parent::boot();
    static::creating(function ($user) {
       Event::fire('user.creating', $user);
    });
}

但当我尝试登录时,我得到以下错误:

Indirect modification of overloaded property App'User::$user has no effect

onUserLogin签名有什么问题?我认为您可以使用$event->user访问用户。。。

如果你想使用事件订阅者,你需要监听Eloquent模型在其生命周期的不同阶段引发的事件。

如果您查看Eloquent模型的fireModelEvent方法,您将看到触发的事件名称是以以下方式构建的:

$event = "eloquent.{$event}: ".get_class($this);

其中,$this是模型对象,$event为事件名称(创建、创建、保存、保存等)。此事件由作为模型对象的单个参数触发。

另一种选择是使用模型观测器-我更喜欢这样做,因为它可以更容易地监听不同的生命周期事件-您可以在这里找到一个示例:http://laravel.com/docs/4.2/eloquent#model-观察员

关于auth.login,当触发此事件时,会传递两个参数-登录的用户记住标志。因此,您需要定义一个接受两个参数的侦听器——第一个参数是用户,第二个参数是记住标志。