The Observers models are great for creating functions specific to the actions performed to the model itself. I use whenever I need to keep the code cohesive and organized in relation to the model, since this action will not impact other classes/models/modules of the system. An example would be to calculate a certain statistical value of the model that is stored in the model itself, whenever it has certain changed fields.
Events can be used to create a mechanism that enables different areas of the system to interact with actions performed in a particular model/module. For example, create an event CompraFinalizada
in an e-commerce system. This event can be listened by different modules of the system, when fired, the module of accounts to pay can generate the boletos and send by email or already register the received payment, a CRM module can send an email or SMS to the customer thanking 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 are putting, sending notifications, I have used one more in the controller and ask the model to perform 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 the notification can or should occur. Nothing prevents the notification in this way from being called within an Observer or Event.
To learn more about working with notifications:
If you used what’s in the documentation in a way that doesn’t have more classes than you need, the first line already says that
Laravel's events provides a simple observer implementation, allowing you to subscribe and listen
that the event is a simple observer, I believe, so that one is variant of the other, not having at home specific gain or loss, maybe other factors can degrade its code performance, for example, an email sending, surely can not measure such performance, because, there are external factors. The code itself the two are the same thing, so I guess there’s no difference!– novic
Create an observer where there is no observer, is a basic development idea, if you create a user on it has a creation observer that can be used to send an email saying that the user has been successfully registered.
– novic
I understand. Thanks for the clarification Virgilio
– Fábio Jânio
It seems that Events are more comprehensive than Observers, since Observers are implemented for Models, whereas Events can be used for anything.
– Wallace Maxters