首页 > 解决方案 > Laravel 监听包事件

问题描述

我想监听一个包触发的事件(Laravel impersonate)。

当我像这样设置我的 EventServiceProvider 时:

<?php

namespace App\Providers;

use App\Listeners\LogImpersonation;
use Illuminate\Support\Facades\Event;
use Lab404\Impersonate\Events\TakeImpersonation;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        TakeImpersonation::class => [
            LogImpersonation::class,
        ]
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();

        //
    }
}

我收到以下错误:

传递给 App\Listeners\LogImpersonation::handle() 的参数 1 必须是 App\Events\TakeImpersonation 的实例,给定 Lab404\Impersonate\Events\TakeImpersonation 的实例

我的日志模拟:

<?php

namespace App\Listeners;

use App\Events\TakeImpersonation;
use App\User;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class LogImpersonation
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Handle the event.
     *
     * @param  TakeImpersonation  $event
     * @return void
     */
    public function handle(TakeImpersonation $event)
    {
        Log::info($event->impersonator->name . ' ingelogd als ' . $event->impersonated);
    }
}

我无法想象我必须移动事件,这是我第一次尝试使用事件,所以我一定错过了一些简单的东西。

标签: phplaraveleventslistener

解决方案


错误消息准确地告诉您出了什么问题:

传递给 App\Listeners\LogImpersonation::handle() 的参数 1 必须是 App\Events\TakeImpersonation 的实例,给定 Lab404\Impersonate\Events\TakeImpersonation 的实例

因此,您的App\Listeners\LogImpersonation::handle()方法期望App\Events\TakeImpersonation给出一个实例,但得到了Lab404\Impersonate\Events\TakeImpersonation.

您需要更新侦听器类以导入正确的类。因此,在顶部的导入中,交换App\Events\TakeImpersonation(这是错误的,不会存在于您的应用程序中)为Lab404\Impersonate\Events\TakeImpersonation(您实际正在侦听的包事件的完全限定名称)。


推荐阅读