为什么事件监听器不在流明开火?

时间:2019-10-09 20:32:33

标签: php events lumen

所以我定义了事件和侦听器类,并将它们注册在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事件类:

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。大家能提供的任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

好吧,我的问题似乎是我在EventServiceProvider中定义了启动方法而没有调用parent::boot()。由于我将代码重构为完全不使用boot方法,因此我将其删除,现在看来效果更好。

答案 1 :(得分:0)

我遇到了问题,可以解决此问题。您应该将以下代码添加到EventServiceProvider类:

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

boot method由UnitTest或我不知道为什么的命令行命令运行时,似乎没有被调用。