Laravel 5.3 - Events or observers?


I have some scenarios where I can use observers to trigger a notification, however, for me it would be indifferent to use observer or else to create an event, a listener and then use this to trigger a notification.

Is there a performance difference between these approaches?

If the above terms are not clear, I am referring to the following approaches respectively:

asked by anonymous 31.10.2016 / 18:51

1 answer


The model observers are great for creating specific functions for the actions performed on the model itself. I use whenever I need to keep the code cohesive and organized in relation to the model, since this particular action will not impact other classes / models / modules of the system. An example would be to calculate a certain statistical value of the template that is stored in the template itself, whenever it has certain fields changed.

Events can be used to create a mechanism that allows different areas of the system to interact with actions performed in a particular model / module. For example, create a CompraFinalizada event in an e-commerce system. This event can be listened to by different system modules when triggered, the accounts payable module can generate the tickets and send by email or already register the payment received, a CRM module can send an email or SMS to the customer thanking him for the purchase and already offering a related offer, the financial module can update the statistical basis of financial analysis and so on.

However, in the specific example you're putting in, sending notifications, I've used one more in the controller and asked the model to make the notification. For example, calling $model->notify(new \App\Notifications\ModelCreated($model)); .

Logically, I make this call on the controller when I'm sure it's the only point where notification can or should occur. Nothing prevents the notification of this form from being called within an observer or event.

To learn more about working with notifications:

25.05.2017 / 14:26