Events
Lightpack provides events support in very friendly manner. For example, sending account confirmation or payment due email both involve utilizing email features. So instead of hard coding email service provider reference in your controllers, you can notify your application components to act on behalf of email related events.
You can use events to promote loose coupling and better code reuse of shareable components.
Defining Listener
To use events in Lighpack, first create a listener. For example, here we create a user event listener.
<?php
namespace App\Events;
class UserCreatedEvent
{
public function handle()
{
// ...
}
}
Registering Listener
Now register this listener in boot/events.php file.
<?php
return [
'user:created' => [
App\Events\UserCreatedEvent::class,
]
];
Notifying Listeners
Now anywhere you fire an event named user:created,
will call App\Events\UserCreatedEvent::handle() method.
<?php
class UserController
{
public function index()
{
event()->fire('user:created');
}
}
Passing Event Data
You can pass any data as second argument to fire() method.
event()->fire('user:created', $user);
Now you can access the event data array in the handle() method of the listener.
public function handle(User $user)
{
// ...
}