-
Notifications
You must be signed in to change notification settings - Fork 3
Listening to Events
Zane H edited this page Feb 21, 2022
·
5 revisions
In order to add a listener to an event you’ll need to ensure your package has an EventServiceProvider
class. It should inherit the base App\Support\EventServiceProvider
class.
<?php
namespace Packages\Rdns\App;
use App\Support\EventServiceProvider;
class RdnsEventServiceProvider extends EventServiceProvider
{
protected $listen = [
// set the event you wish to listen to as the key in the mapping:
CreatedEvent::class => [
// And then an array of listeners as the value. You can have multiple listeners for the same event:
EventLogger::class,
SyncToServer::class,
],
DeletedEvent::class => [
EventLogger::class,
DeleteFromServer::class,
],
];
}
Add your new EventServiceProvider
to your package's providers.php
file, refer to Service Providers for an example. Only one EventServiceProvider
is needed, but you can have multiple if you wish to organize your package that way.
Add the listener classes you want listening to the event. Listener classes must have a public handle method with the event as the parameter. Example:
<?php
namespace Packages\Rdns\App;
class DeleteFromServer {
//the argument for the handler needs to be the event the listener is tied to in the EventServiceProvider
public function handle (DeletedEvent $event) {
//the logic for the event listener runs in the handle method
}
}
Then add the event class you wish to listen to and the listener to your EventServiceProvider
's mapping.