Search code examples
phpeventslumen

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


So I have event and listener classes defined as well as having them registered in the $listen array in EventServiceProvider.php. Here is the code:

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

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

and then in EventServiceProvider's boot method I have the following:

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

here is the EpisodeCreated event class:

namespace App\Events;

use App\Models\Episode;

class EpisodeCreated extends Event {
    public $episode;

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

and finally the listener:

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());
    }

}

Lastly, I wrote the following unit test to make sure that the event is firing. It doesn't seem to be:

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

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

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

I get an error saying that the event never got dispatched when I run phpunit. Also I added echo debug statements and while the EpisodeCreated object is being created, the NewEpisodeListener is not being fired off. Any help you guys can give would be greatly appreciated.


Solution

  • Well, my problem seems to be that I defined the boot method in EventServiceProvider without calling parent::boot(). Since I refactored my code to not use the boot method at all, I removed it and it seems to be working better now.