Refactoring to Events
I know, we're all used to seeing that kind of messy code with a lot of ifs and elses, right?
But today we're going to try to change this a little bit.
Well, let's start with a sample. It's a class that handles Stripe webhooks.
No, you would never in your entire life guess that I got this code from the Cashier repository. Never.
That's fine, right? If we receive an event called customer.subscription.deleted, our method handleCustomerSubscriptionDeleted will handle it!
But that's only fine while your application is starting and you don't need to handle much. What if we need to receive all Stripe methods? Should we take the same approach?
Nope!
We have better ways to handle that, thanks to Laravel Events.
All we need to do to write more consistent and understandable code is to create an event for every hook that we want to receive.
So if you need to listen to Stripe's customer subscription deleted hook, you create an event called StripeCustomerSubscriptionDeleted, and then create the listeners that handle that event.
This makes our controller thinner, because it moves responsibilities to event listeners:
Now, for every event that Stripe sends us, the controller will try to call an event. We just need to create and handle it.
Then we create our event:
And our listener:
final
Now that we have our event and listener, we need to tell Laravel how to handle them. To do this, we just add them to the EventServiceProvider:
And that's it!
You can apply this in countless situations where you're handling a lot of conditions.
Just create events and separate your handlers. Your code will be cleaner and easier to understand. And you can also run some of those listeners in queues, so your users don't need to wait for a response that takes a long time to return.
Of course, my example only explains one situation. I really think this should only be applied if you have a lot of events and listeners to handle in your workflow. Otherwise, just keep the default approach.
Originally published on Medium
Comments