Yesterday, I walked through a hypothetical situation with an event that had listeners where only a subset applied to each user.
Here's a real-world example, which has a similar "shape" of problem, even if the specifics seem different at first glance.
The owner of an app wanted to know if a lower-privileged admin (let's call them a manager) modified client record.
They needed this for billing oversight and abuse protection, but they had some additional requirements:
- No notifications for their own changes
- Only notify if certain key fields were changed
Where would we put this conditional logic?
One approach would be to use a simple queued notification and then put all the conditional logic in the controller to decide whether to send the notification or not.
This isn't great, since it adds more logic to the controller that isn't really about the controller action. And this gets even messier as additional ways to create, update, or delete clients are added throughout the app.
Instead, as with yesterday's solution, we fire an event, wire up a listener, and then inside the listener is the conditional logic to decide if it needs to send the notification.
I like that the controller is dispatching clearly-named events like ClientCreated
, ClientUpdated
, or ClientDeleted
.
And then we use a well-named listener, like NotifyAdminOfManagerCreatedClient
, to encapsulate the conditional logic and communicate that this listener only applies in a specific situation.
Two days in a row I've talked about events and listeners, so I feel the need to restate that we are cautious about not overusing events and listeners. I don't want to give the impression we use them a lot, but this is a use case that improves readability and intent, even if there's a simple one-to-one relationship between the event and listener.
Here to help,
Joel
P.S. Laravel has an excellent manual, but it's general purpose advice. We wrote a whole book on validation rules which doesn't just explain how they work, but why and when to use them as well.