May Sale! All accounts are 40% off this week.

ovvessem's avatar

Event + Listener or Model Observer

Hi community,

I am currently building a new application which should interact with a third application through an API. For example if a new customer is created it should also create/provision it in the third party application and send a notification to the new customer.

I have read about Event + Listener and Model Observers in the Laravel documentation and am curious what is best practise to execute the provisioning. From what I understand an Observer is used to group all of the listeners into a single class.

Should I use a model observer and put the necessary actions (provision customer en and notification) in the e.g. created handle event or should I define a protected dispatchesEvents on the Model and generate the Event en Listener where per action there is one listener?

Love to hear best practised from the community. Thanks in advance.

0 likes
1 reply
D9705996's avatar

@ovvessem - model observers allow you to hook into the laravel model events lifecycle, e.g. creating, created, updating, deleting, etc.

This allows you to easily automate your own business logic when these events occur, e.g. when a new User is created send you an email.

Events and Listeners enable you to fire off events anywhere in you application and have one or more listeners handle these events.

You can combine both techniques e.g. in your model observer you could fire a NewCustomerCreated event in the created method on you CustomerObserver. In your event configuration you can then setup your listeners to take action e.g. CreateNewCustomerInAPI that receives the created user to enable you to do whatever you need with your third party.

The couple of benefits are

  1. You can add new listeners to the array as you need them, e.g. if you need to email the customer when they are added you just add a new listener. You other code doesn't need to change

  2. You can queue you events in something like horizon so long running tasks can be executed in the background.

The downside are

  1. Your code can become quite fragmented as there a little bits all over your project so harder to debug, especially if you have to revisit in 6 months Tim

  2. Testing becomes a bit harder as you have to test that the events and listeners are firing correctly

There is a good article by Adam Wathan on the last point

https://adamwathan.me/2016/08/15/three-approaches-to-testing-events-in-laravel/

In my opinion they are a great option for complex systems but should only be used where needed (it's easy to make everything an event and you literally have no idea what's happening in your app)

1 like

Please or to participate in this conversation.