Event
Laravel's Events provides a simple Observer pattern implementation, allowing you to subscribe and listen to various events that occur within your application. Event classes are typically stored in the
app/Eventsdirectory, while their Listeners are stored inapp/Listenersdirectory. Don't worry if you don't see these directories in your application as they will be created automatically as you generate events and listeners using Artisan console commands.
Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can raise an
App\Events\OrderShippedevent which a listener can receive and use to dispatch a Slack notification.
Dispatch Event
For example, dispatch an event named search.updated and pass $model argurment. All Listener classes registered with the search.updated event will be processed.
<?php
app('events')->dispatch('search.updated', [$model]);
Listeners
Define Event Listener
<?php
// file packages/metafox/blog/src/Listeners/SearchUpdatedListener.php
namespace MetaFox\Blog\Listeners;
class SearchUpdatedListener
{
/**
* Handle event
*/
public function handle($model)
{
return 1;
}
}
To improve performance, MetaFox requires manual event listener registration via PackageSettingListener class.
<?php
namespace MetaFox\ToDo\Listeners;
class PackageSettingListener extends BasePackageSettingListener {
/**
* Get array of events
*/
public function getEvents()
{
return [
'search.updated' => [
SearchUpdatedListener::class,
],
];
}
}Response
TBD
For futher info, please read Laravel Event (opens in a new tab)
Bail
Sometimes, you may need dispatcher to stop running other listeners whenever a listener returns a not-null value.
<?php
$response = app('events')->dispatch('search.updated', [$model], $bail=true);
In the above sample code, with $bail=true parameter, at the first time a listener returns not-null value, the dispatcher will stop running remaining registered Listener and returns to $response value.