Reputation: 10886
I'm building a ticketSystem api in Laravel. And I've got a lot of events. And I'm wondering if I'm doing it right. So for example when a user is created it fires the event: CreateUserEvent
That event has a couple of listeners like:
I've got for almost every crud things an event with multiple listeners. Is this the normal way of doing this kind of things? In my controllers I almost fire only events.
I've already watched a couple of videos about events for example (https://laracasts.com/series/intermediate-laravel/episodes/3) But I'm still a bit confused.
So basically my question is: Is it normal that your webapp exist out of a lot of events? If it's not where do you use events?
Upvotes: 3
Views: 467
Reputation: 146191
Actually, you are making it complex. Use the single event listener for a single event and do the actions in that event handler. For example:
// In EventServiceProvider
protected $listen = [
'user.created' => ['App\Handlers\Events\UserEvents@userCreated'],
],
Somewhere in your app:
// ...
if($user = User::create($request->all())) {
app('event')->fire('user.created', $user);
}
...
The handler App\Handlers\Events\UserEvents@userCreated
:
<?php namespace App\Handlers\Events;
use App\User;
use App\Package;
use App\Services\Mail\UserMailer;
class UserEvents {
protected $mailer = null;
protected $package = null;
public function __construct(UserMailer $mailer, Package $package)
{
$this->mailer = $mailer;
$this->package = $package;
}
public function userCreated(User $user)
{
$this->package->create($user); // <-- An action to be taken
$this->mailer->notifyUser($user); // <-- Another action to be taken
}
}
So, this way, you can handle your events and use the handler to take additional actions for you on a particular event.
Upvotes: 1