为什么事件侦听器不在 Lumen 中启动?

Why isn't the event listener firing off in Lumen?

所以我定义了事件和侦听器 classes,并在 EventServiceProvider.php 的 $listen 数组中注册了它们。这是代码:

use App\Events\EpisodeCreated;
use App\Listeners\NewEpisodeListener;

use Event;
class EventServiceProvider extends ServiceProvider {
    protected $listen = [
        EpisodeCreated::class => [
            NewEpisodeListener::class
        ]
    ];
}

然后在 EventServiceProvider 的引导方法中,我有以下内容:

public function boot() {
    Episode::created(function($episode) {
        Event::fire(new EpisodeCreated($episode));
    });
}

这是 EpisodeCreated 事件 class:

namespace App\Events;

use App\Models\Episode;

class EpisodeCreated extends Event {
    public $episode;

    public function __construct(Episode $episode) {
        $this->episode = $episode;
    }
}

最后是听众:

namespace App\Listeners;

use App\Events\EpisodeCreated;
use App\Facades\EventHandler;
use App\Http\Resources\ShowResource;

class NewEpisodeListener {

    public function __construct() {

    }

    public function handle(EpisodeCreated $event) {
        EventHandler::sendNewEpisode((new ShowResource($event->episode->show))->toArray());
    }

}

最后,我编写了以下单元测试以确保事件正在触发。好像不是:

public function testNewEpisodeEventFiredOff() {
    Event::fake();

    $show = factory(Show::class)->create();
    $episode = factory(Episode::class)->create(['show_id' => $show->id]);

    Event::assertDispatched(EpisodeCreated::class);
}

我收到一条错误消息,说当我 运行 phpunit.我还添加了 echo 调试语句,并且在创建 EpisodeCreated 对象时,没有触发 NewEpisodeListener。非常感谢你们能提供的任何帮助。

好吧,我的问题似乎是我在EventServiceProvider中定义了引导方法而没有调用parent::boot()。因为我重构了我的代码以完全不使用引导方法,所以我删除了它,现在它似乎工作得更好了。

我遇到了问题,可以解决这个问题。您应该将以下代码添加到您的 EventServiceProvider class:

public function register()
{
    $this->boot();
}

似乎 boot method 在被 UnitTest 或 Command-line 命令 运行 调用时没有调用我不知道为什么。