Event Bus
1 min read · last updated atWeb applications are eventful by nature. At some point, it will need to handle an incoming request and generate a response. There we have two important events, that components of your application might want to know about.
The component responsible for distributing events to components that want to know about them is usually called Event Bus.
How It works
Defining The Payload
Events are usually simple classes like the ones below:
Events are plain PHP classes, that optionally use the Dispatchable
trait.
Events extend the ApplicationEvent
class:
Dispatch An Event
These event classes can then be published or dispatched onto the event bus. See the examples below for how different frameworks implement this.
An event can be dispatched either using
if your event class uses the Dispatchable
-trait mentioned earlier.
Otherwise use the Event
alias:
which could be more convenient for autocompletion and static analysis, since it uses less magic to resolve the constructor arguments.
Spring’s ApplicationEventPublisher
is responsible for publishing events and can be injected into any class that implements the ApplicationEventPublisherAware
interface:
Handle An Event
To handle events, your application defines and registers listeners. When dispatching an event, the event bus iterates through all listeners interested in that type of event and executes their logic:
A listener is a class with a __invoke
or handle
method like this one:
Make sure to specify the parameter type of the event, since Laravel uses this information to detect which listener gets called for a event.
Such a class can be created using the artisan
tool:
Instead of explicitly registering listeners, we can
Learn more at https://laravel.com/docs/events.
Listeners are beans that implement the ApplicationListener
:
Learn more at https://docs.spring.io/spring-framework/reference/core/beans/context-introduction.html#context-functionality-events