w3resource

Laravel (5.7) Events

Basics of Events and Listeners

In this section, we'll explore Laravel's way of implementing events and listeners in the core framework. If you're familiar with the architecture of Laravel, you probably know that Laravel implements the concept of a service provider that allows you to inject different services into an application.

Similarly, Laravel provides a built-in EventServiceProvider.php class that allows us to define event listener mappings for an application.

Go ahead and pull in the app/Providers/EventServiceProvider.php file.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\SomeEvent' => [
        'App\Listeners\EventListener',
        ],
    ];
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        //
    }
}

Let's have a close look at the $listen property, which allows you to define an array of events and associated listeners. The array keys correspond to events in a system, and their values correspond to listeners that will be triggered when the corresponding event is raised in a system.

I prefer to go through a real-world example to demonstrate it further. As you probably know, Laravel provides a built-in authentication system that facilitates features like login, register, and the like.

Assume that you want to send the email notification, as a security measure, when someone logs into the application. If Laravel didn't support the event listener feature, you might have ended up editing the core class or some other way to plug in your code that sends an email.

In fact, you're on the luckier side as Laravel helps you to solve this problem using the event listener. Let's revise the app/Providers/EventServiceProvider.php file to look like the following.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'Illuminate\Auth\Events\Login' => [
        'App\Listeners\SendEmailNotification',
        ],
    ];
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        //
    }
}

It's the handle method that will be invoked with appropriate dependencies whenever the listener is triggered. In our case, the $event argument should contain contextual information about the login event—logged in user information.

And we can use the $event object to carry out further processing in the handle method. In our case, we want to send the email notification to the logged in user.

The revised handle method may look something like:

public function handle(Login $event)
{
    // get logged in user's email and username
    $email = $event->user->email;
    $username = $event->user->name;
     
    // send email notification about login
}

So that's how you're supposed to use the events feature in Laravel. From the next section onwards, we'll go ahead and create a custom event and associated listener class.

Create a Custom Event

The example scenario that we're going to use for our example is something like this:

  • An application needs to clear caches in a system at certain points. We'll raise the CacheClear event along with the contextual information when an application does the aforementioned. We'll pass cache group keys along with an event that was cleared.
  • Other modules in a system may listen to the CacheClear event and would like to implement code that warms up related caches.

Let's revisit the app/Providers/EventServiceProvider.php file and register our custom event and listener mappings.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        'App\Events\ClearCache' => [
        'App\Listeners\WarmUpCache',
        ],
    ];
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        //
    }
}

As you can see, we've defined the App\Events\ClearCache event and associated listener class App\Listeners\WarmUpCache under the $listen property.

Next, we need to create associated class files. Recall that you could always use the artisan command to generate a base template code.

php artisan event:generate

That should have created the event class at app/Events/ClearCache.php and the listener class at

app/Listeners/WarmUpCache.php.

With a few changes, the app/Events/ClearCache.php class should look like this:

<?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 ClearCache
{
    use Dispatchable, InteractsWithSockets, SerializesModels;
     
    public $cache_keys = [];
    /**
     * Create a new event instance.
     *
     * @return void
     */
    public function __construct(Array $cache_keys)
    {
        $this->cache_keys = $cache_keys;
    }
    /**
     * Get the channels the event should broadcast on.
     *
     * @return Channel|array
     */
    public function broadcastOn()
    {
        return new PrivateChannel('channel-name');
    }
}

As you've probably noticed, we've added a new property $cache_keys that will be used to hold information that'll be passed along with an event. In our case, we'll pass cache groups that were flushed.

Next, let's have a look at the listener class with an updated handle method at app/Listeners/WarmUpCache.php.

<?php
namespace App\Listeners;
use App\Events\ClearCache;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
class WarmUpCache
{
    /**
     * Create the event listener.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    /**
     * Handle the event.
     *
     * @param  ClearCache  $event
     * @return void
     */
    public function handle(ClearCache $event)
    {
        if (isset($event->cache_keys) && count($event->cache_keys)) {
            foreach ($event->cache_keys as $cache_key) {
                // generate cache for this key
                // warm_up_cache($cache_key)
            }
        }
    }
}

When the listener is invoked, the handle method is passed with the instance of the associated event. In our case, it should be the instance of the ClearCache event that will be passed as the first argument to the handle method.

Next, it's just a matter of iterating through each cache key and warming up associated caches.

Now, we have everything in place to test things against. Let's quickly create a controller file at app/Http/Controllers/EventController.php to demonstrate how you could raise an event.

<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use App\Library\Services\Contracts\CustomServiceInterface;
use App\Post;
use Illuminate\Support\Facades\Gate;
use App\Events\ClearCache;
class EventController extends Controller
{
    public function index()
    {
        // ...
         
        // you clear specific caches at this stage
        $arr_caches = ['categories', 'products'];
         
        // want to raise ClearCache event
        event(new ClearCache($arr_caches));
         
        // ...
    }
}

Firstly, we've passed an array of cache keys as the first argument while creating an instance of the ClearCache event. The event helper function is used to raise an event from anywhere within an application. When the event is raised, Laravel calls all listeners listening to that particular event.

In our case, the App\Listeners\WarmUpCache listener is set to listen to the App\Events\ClearCache event. Thus, the handle method of the App\Listeners\WarmUpCache listener is invoked when the event is raised from a controller. The rest is to warm up caches that were cleared!

So that's how you can create custom events in your application and work with them.

What Is an Event Subscriber?

The event subscriber allows you to subscribe multiple event listeners in a single place. Whether you want to logically group event listeners or you want to contain growing events in a single place, it's the event subscriber you're looking for.

If we had implemented the examples discussed so far in this article using the event subscriber, it might look like this.

<?php
// app/Listeners/ExampleEventSubscriber.php
namespace App\Listeners;
class ExampleEventSubscriber
{
    /**
     * Handle user login events.
     */
    public function sendEmailNotification($event) {
        // get logged in username
        $email = $event->user->email;
        $username = $event->user->name;
         
        // send email notification about login...
    }
    /**
     * Handle user logout events.
     */
    public function warmUpCache($event) {
        if (isset($event->cache_keys) && count($event->cache_keys)) {
            foreach ($event->cache_keys as $cache_key) {
                // generate cache for this key
                // warm_up_cache($cache_key)
            }
        }
    }
    /**
     * Register the listeners for the subscriber.
     *
     * @param  Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($events)
    {
        $events->listen(
            'Illuminate\Auth\Events\Login',
            'App\Listeners\ExampleEventSubscriber@sendEmailNotification'
        );
         
        $events->listen(
            'App\Events\ClearCache',
            'App\Listeners\ExampleEventSubscriber@warmUpCache'
        );
    }
}

It's the subscribe method that is responsible for registering listeners. The first argument of the subscribe method is the instance of the Illuminate\Events\Dispatcher class that you could use to bind events with listeners using the listen method.

The first argument of the listen method is an event that you want to listen to, and the second argument is a listener that will be called when the event is raised.

In this way, you can define multiple events and listeners in the subscriber class itself.

The event subscriber class won't be picked up automatically. You need to register it in the EventServiceProvider.php class under the $subscriber property, as shown in the following snippet.

<?php
namespace App\Providers;
use Illuminate\Support\Facades\Event;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
class EventServiceProvider extends ServiceProvider
{
    /**
     * The subscriber classes to register.
     *
     * @var array
     */
    protected $subscribe = [
        'App\Listeners\ExampleEventSubscriber',
    ];
    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        //
    }
}

Previous: Laravel (5.7) Collections
Next: Laravel (5.7) File Storage



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/laravel/events.php