Listeners
While handle() methods project data to the database on events, you may want to extract certain behaviors into a dedicated class to be shared by multiple events; you can do so by registering the listener in your AppServiceProvider.
1Verbs::listen(MyListener::class);
You can use listeners on specific events, the Event class, or event interfaces
1interface IsSpecialEvent {} 2 3class NormalEvent extends Event {} 4 5class SpecialEvent extends Event implements IsSpecialEvent {} 6 7// ... 8 9class MyListener10{11 public function listenForJustNormalEvent(NormalEvent $event)12 {13 // Only gets triggered when the `NormalEvent` class is fired14 }15 16 public function listenForAnySpecialEvent(IsSpecialEvent $event)17 {18 // Gets triggered when any event that implements `IsSpecialEvent` is fired19 }20 21 public function listenForAllEvents(Event $event)22 {23 // Gets triggered when any Event fires24 }25}
Say you have an analytics process, or some secondary reporting functionality that you want to add. Sometimes it doesn't make sense for those to exist on the event itself. Now you can do something like:
1class AnalyticsProjector2{3 #[On(Phase::Handle)]4 public function onDownload(ProductDownloaded|ProductUpdated|ProductDiscontinued $event)5 {6 Analytics::incrementDownloads();7 }8}