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

时间:2015-12-14 18:27:49

标签: php laravel events laravel-5 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 ...

来访问用户

1 个答案:

答案 0 :(得分:0)

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

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

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

其中 $ this 是模型对象, $ event 是事件名称(创建,创建,保存,保存等)。使用单个参数触发此事件,该参数是模型对象。

另一种选择是使用模型观察者 - 我更喜欢事件订阅者,因为它可以更轻松地监听不同的生命周期事件 - 您可以在此处找到一个示例:http://laravel.com/docs/4.2/eloquent#model-observers

关于 auth.login ,触发此事件时,会传入2个参数 - 用户,并且记住标记。因此,您需要定义一个带有2个参数的侦听器 - 首先是用户,第二个是remember标志。

相关问题