The Laravel Events and Listeners is a simple implementation of the observer design pattern. There is also Model Observer which is a similar implementation but specifically for the Eloquent models.
In this lesson, we’ll learn the observer pattern with examples of how it can be implemented in a Laravel project.
Observer Pattern Explained
The observer pattern is majorly about monitoring the state of the system and doing something in response to change in that state.
For example, say you’re building an invoice management system and you want the system to make audit logs (also called audit trails) that record users activities and the actions they take in the system.
For example, when a user creates an invoice, it is recorded that user John Doe created an invoice today at 12 PM, when a user updates an invoice, it is recorded, etc.
The object being observed (Invoice in our example), is often referred to as the subject or publisher or observable. Certain events are fired when the state of the observable changes. The parts of your code that listen to the events fired when the state of the observable changes are called subscribers or observers.
Benefits of the Observer Design Pattern
- It supports loose coupling between between the observable and the observers
- It makes it easy for you to handle cases where multiple objects depend on the state of an object. That is, one observable can have multiple observers
How the observer pattern works (simplified)
A simplified diagram of the observer design pattern
Watch the lesson
The video explains the implementation of the observer pattern, with the codes. The article basically gives explanations without the codes, hence, you should watch the video to see the codes and try implementing them yourself.
Laravel Events and Event Listeners
How to Generate Events and Listeners in Laravel
Generating the Event and Lister files
- make:event: Artisan command to generate Event
- make:listener: Artisan command to generate Listener
- Register the events and listeners in the listen array property of the App\Providers\EventServiceProvider. You can also register events and listeners manually first and then use event:generate Artisan command to create the Event and Listener files.
Tip: Use event:list artisan command to display a list of all events and listeners registered by your application.
You can define a serializable public member that is injected in the constructor method of the event class when the event is being dispatched. Oftentimes this public member is an Eloquent ORM model.
The event listeners receive instances of the event they subscribed to in their handle method.
Tip: To stop the propagation of an event to other listeners, return false from your listener’s handle method.
You may call the static dispatch method on event to dispatch an event. Arguments passed to the dispatch method will be passed to the event’s constructor.
Laravel Model Observers
Model observers are a kind of specially packaged implementation of the same observer pattern. It is ideal to use the model observer if you are listening for many events on a given Eloquent model.
Note that this is different from having many subscribers listening to a single Observable. Model observers are ideal for listening to different kinds of events from a single Observable.
How to create Model Observer in Laravel
make:observer Artisan command is used to generate a model observer. Example: php artisan make:observer InvoiceObserver –model=Invoice
This creates the Observer class in App\Observers namespace where you can listen to different events from the model being observed. The events you can listen to include:
Registering the Model Observer
After creating the observer class, you need to register it in the boot method of your application’s App\Providers\EventServiceProvider service provider:
I don’t know why I find the order counter-intuitive because I expected it to be InvoiceObserver::observe(Invoice::class) since it is the observer(InvoiceObserver) that is observing the model(Invoice).
What we’ve done so far is the basics of Event and Listeners in Laravel. I encourage you to dive into the official documentation to understand other things not covered in this lesson, such as
- Queued Event Listeners,
- Event Listeners and Database Transactions,
- Handling Failed Jobs when your queued event listeners fail,