为什么我的事件侦听器没有在 laravel 5 中触发?

Roh*_*han 5 php events laravel laravel-5 laravel-events

因此,当我正在处理的 laravel 5 应用程序中创建新订单时,我试图记录一些简单的事情。

所以我有一个OrderWasCreated看起来像这样的事件:

<?php

namespace App\Events;

use App\Events\Event;
use Illuminate\Queue\SerializesModels;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;

use App\Order;

class OrderWasCreated extends Event
{
    use SerializesModels;

    public $order;

    /**
     * OrderWasCreated constructor.
     */
    public function __construct(Order $order)
    {
        $this->order = $order;
    }


    /**
     * Get the channels the event should be broadcast on.
     *
     * @return array
     */
    public function broadcastOn()
    {
        return [];
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我有OrderEventListener它看起来像这样:

<?php

namespace App\Listeners;

use App\Events\OrderWasCreated;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

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

    public function subscribe(Dispatcher $events)
    {
        $events->listen(
            'App\Events\OrderWasCreated',
            'App\Listeners\OrderEventListener@onOrderWasCreated'
        );
    }

    /**
     * Handle the event.
     *
     * @param  OrderWasCreated  $event
     * @return void
     */
    public function onOrderWasCreated(OrderWasCreated $event)
    {
        \Log::info('Order was created event fired');
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的OrderController,我的 store 方法中有这个:

    event(new OrderWasCreated($order));
Run Code Online (Sandbox Code Playgroud)

然而,当我创建新订单时,我在日志文件中看不到任何内容。我错过了什么?

Mar*_*łek 4

可能您还没有添加到的属性OrderEventListener中,它应该如下所示:subscribeEventServiceProvider

protected $subscribe = [
   'App\Listeners\OrderEventListener',
];
Run Code Online (Sandbox Code Playgroud)

如果您添加了,请运行php artisan clear-compiled以确保您的应用程序使用当前版本的类。

  • php artisanclear-compiled 和 php artisanqueue:restart 非常重要。容易忘记的命令。 (2认同)