Laravel 5 事件处理程序未触发

2022-08-30 20:16:13

所以我正在尝试新的Laravel 5 Event方法。

在我的存储库中,我正在触发事件“KitchenStored”,如下所示:

//  Events
use App\Events\KitchenStored;

class EloquentKitchen implements KitchenInterface {

    public function store($input) {
        $kitchen        = new $this->kitchen;
        $kitchen->name  = $input['name'];
        $kitchen->save();

        \Event::fire(new KitchenStored($kitchen));

        return $kitchen;
    }

哪个成功触发此事件:

<?php namespace App\Events;

use App\Events\Event;

use Illuminate\Queue\SerializesModels;

class KitchenStored extends Event {

    use SerializesModels;

    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct($kitchen)
    {
        $this->kitchen  = $kitchen;
    }

}

但是,它不会链接到此处理程序:

<?php namespace App\Handlers\Events;

use App\Events\KitchenStored;

use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldBeQueued;

class AttachCurrentUserToKitchen {

    /**
     * Create the event handler.
     *
     * @return void
     */
    public function __construct()
    {
        dd('handler');
    }

    /**
     * Handle the event.
     *
     * @param  KitchenStored  $event
     * @return void
     */
    public function handle(KitchenStored $event)
    {
        //
    }

}

我知道,因为dd('处理程序');在请求生命周期内不触发。

我已在此处向其侦听器注册了该事件:

<?php namespace App\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider {

    /**
     * The event handler mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        App\Events\KitchenStored::class => [
            App\Handlers\Events\AttachCurrentUserToKitchen::class
        ]
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events)
    {
        parent::boot($events);
        Event::listen('App\Events\KitchenStored',
                    'App\Handlers\Events\AttachCurrentUserToKitchen');
    }

}

任何人都可以更好地解释这个过程,这样我就可以继续使用迄今为止最干净的代码?

非常感谢


答案 1

在 中,使用表示法引用类时包括前导符:EventServiceProvider.php\::class

protected $listener = [
    \App\Events\KitchenStored::class => [
      \App\Handlers\Events\AttachCurrentUserToKitchen::class,
    ],
];

您还可以添加语句并保持侦听器映射简短:use

use App\Events\KitchenStored;
use App\Handlers\Events\AttachCurrentUserToKitchen;
...
protected $listener = [
    KitchenStored::class => [
      AttachCurrentUserToKitchen:class,
    ],
];

或者只使用字符串表示法:

protected $listener = [
    'App\Events\KitchenStored' => [
      'App\Handlers\Events\AttachCurrentUserToKitchen',
    ],
];

答案 2

如果运行 ,事件处理程序应开始侦听。php artisan optimize

感谢来自larachat slack频道的mattstauffer。


推荐