Organising Your Application's Logic with Laravel Events and Listeners
Laravel events and listeners provide a simple and elegant way to organize your application's logic and keep your code organized and decoupled. Events are used to broadcast notifications that something has occurred in your application, while listeners are used to handle the logic that should be executed in response to those events. In this tutorial, we'll go over the basics of working with events and listeners in Laravel.
First, let's create a new event. We'll call it "OrderCreated" and it will be dispatched every time a new order is placed in our application.
Here's an example of an event class :
<?php
namespace App\Events;
use Illuminate\Broadcasting\Channel;
use Illuminate\Queue\SerializesModels;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
class OrderCreated
{
use Dispatchable, InteractsWithSockets, SerializesModels;
public $order;
/**
* Create a new event instance.
*
* @param $order
*/
public function __construct($order)
{
$this->order = $order;
}
}
As you can see, the event has a public property called $order
that stores the order data.
Next, let's create a listener for this event. A listener class can contain one or multiple methods, each one will handle the logic of the event.
<?php
namespace App\Listeners;
use App\Events\OrderCreated;
use App\Notifications\OrderPlaced;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class SendOrderConfirmation
{
/**
* Handle the event.
*
* @param OrderCreated $event
* @return void
*/
public function handle(OrderCreated $event)
{
// send a notification to the customer with the order details
$event->order->user->notify(new OrderPlaced($event->order));
}
}
This listener class has a method named handle
that will take the OrderCreated
event as parameter, and it's responsible for sending a notification to the customer with the order details.
Now we need to register the listener and connect it to the event , and we can do that in the EventServiceProvider located in the app/Providers
folder.
protected $listen = [
OrderCreated::class => [
SendOrderConfirmation::class,
],
];
This is how you can connect the listener to the event. In your application, you can dispatch events using the Event
facade or by using the helper function event()
.
event(new OrderCreated($order));
Or by using the event facade :
Event::dispatch(new OrderCreated($order));
And that's it! With this simple setup, you have created an event that can be dispatched throughout your application and handled by one or multiple listeners. This allows you to separate your application's logic into small, manageable pieces that can be reused and composed in different ways.
It's also worth noting that listeners can be queueable, which allows you to run the logic in the background using Laravel's queue worker. This can be useful for tasks that may take a long time to complete, such as sending an email or processing an image. To make a listener queueable, you can simply implement the ShouldQueue
interface on the listener class:
class SendOrderConfirmation implements ShouldQueue
{
// ...
}
Additionally, you can also prioritize events by using the EventSubscribe
facade. You can use EventSubscribe::listen
method which allow you to specify the priority of events by passing an array of event names and their associated listeners as the first argument, and an array of priority levels as the second argument.
EventSuscribe::listen(
[
OrderCreated::class => [
SendOrderConfirmation::class,
SendAdminNotification::class,
],
],
'high'
);
Another powerful feature of events is that they can be broadcasted to other systems, such as WebSockets, which allows for real-time communication between the server and clients. You can do this by implementing the ShouldBroadcast
interface on the event class and adding a broadcastOn method that returns the channels on which the event should be broadcasted.
In conclusion, Laravel events and listeners provide a flexible and powerful way to organize your application's logic. They allow you to separate concerns and make your code more manageable and reusable. You can also prioritize events and broadcast them to other systems. You can use this technique to handle all sort of event-based functionality, such as notifications, or analytics, and many other use-cases.