Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何在Laravel 5.1中将模型事件添加到事件订阅服务器类_Php_Laravel_Events_Laravel 5_Laravel 5.1 - Fatal编程技术网

Php 如何在Laravel 5.1中将模型事件添加到事件订阅服务器类

Php 如何在Laravel 5.1中将模型事件添加到事件订阅服务器类,php,laravel,events,laravel-5,laravel-5.1,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)

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

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);
    });
}
我将以下内容添加到用户模型的引导方法中,如下所示:

 protected $subscribe = [
    'App\Listeners\UserEventListener',
];
public static function boot()
{
    parent::boot();
    static::creating(function ($user) {
       Event::fire('user.creating', $user);
    });
}
但当我尝试登录时,会出现以下错误:

间接修改重载属性App\User::$User无效


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

访问用户。如果您想使用事件订阅服务器,您需要了解雄辩的模型在其生命周期的不同阶段触发的事件

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

$event = "eloquent.{$event}: ".get_class($this);
其中,$this是模型对象,$event是事件名称(创建、创建、保存、保存等)。此事件由一个作为模型对象的参数触发

另一种选择是使用模型观察者——我更喜欢使用模型观察者而不是事件订阅者,因为它使监听不同的生命周期事件变得更容易——您可以在这里找到一个示例:


关于身份验证登录,当触发此事件时,将传递两个参数-登录的用户,以及记住标志。因此,您需要定义一个接受两个参数的侦听器-第一个参数是用户,第二个参数是记住标志。

这是关于laravel 5.1的问题。我认为模型观察者更多的是与Laravel5有关。他们仍然存在于5.1中,并没有被弃用。但正如我所说,这只是选项之一,如果您愿意,可以随意使用事件订阅者。