Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Auto discovery of events in Laravel

April 26, 2020 ·

In this article, I’ve written about how to use event subscribers or observer pattern in Laravel.

So basically, one can write the Events and register them along with their listeners in app/Providers/EventServiceProvider class, under $listen like so.

/**
 * The event listener mappings for the application.
 *
 * @var array
 */
protected $listen = [
    'App\Events\OrderCanceled' => [
        'App\Listeners\SendOrderCancelEmail',
        'App\Listeners\InitiateOrderRefund',
    ],
];

As the Events grows so as this $listen property. And there would be a good chance, you might forget to register the event.

Auto Discovering Events

To overcome the above issue, Laravel comes with the auto discovery of the events and respective listeners of those events. But the feature is not enabled by default.

This can be enabled by overriding the shouldDiscoverEvents method of your application’s app/Providers/EventServiceProvider by returning true from it like so.

/**
 * Determine if events and listeners should be automatically discovered.
 *
 * @return bool
 */
public function shouldDiscoverEvents()
{
    return true;
}

Once done, Laravel will automatically find and register your events and listeners by scanning your application’s Listeners directory. In addition, any explicitly defined events listed in the EventServiceProvider will still be registered.

Behind the scenes, Laravel identfies events and listeners by scanning Event and Listener directories using PHP’s Reflection.

Auto-discovery with custom directories

By default, all listeners within your application’s Listeners directory will be scanned. If you would like to define additional directories to scan, you may override the discoverEventsWithin method in your EventServiceProvider like so.

/**
 * Get the listener directories that should be used to discover events.
 *
 * @return array
 */
protected function discoverEventsWithin()
{
    return [
        $this->app->path('Listeners'),
    ];
}
Learn the fundamentals of PHP 8 (includes 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-read guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!

Comments?