Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use events in Laravel

I am new to laravel, and I have a question about the usage of events.

As far as I understand, events are used when some actions such as registering users occur and handle logic following those actions such as sending a confirmation email.

But what I do not understand is that why can't I just create a helper function which would handle those actions instead of creating event and listener files.

In other words, what is the advantages of using events?

Thank you.

like image 529
smchae Avatar asked Jan 11 '18 00:01

smchae


2 Answers

Using events and listeners just another approach to implement that use observer pattern. Of course it has its own advantages. As the laravel document said:

Events serve as a great way to decouple various aspects of your application, since a single event can have multiple listeners that do not depend on each other. For example, you may wish to send a Slack notification to your user each time an order has shipped. Instead of coupling your order processing code to your Slack notification code, you can simply raise an OrderShipped event, which a listener can receive and transform into a Slack notification.

like image 117
Vũ Nhật Anh Avatar answered Nov 12 '22 11:11

Vũ Nhật Anh


Using events and listeners instead of helpers can have 2 additional benefits:

  1. Stopping The Propagation Of An Event (without extra conditionals)
  2. Queuing the implementation login

    -> Mails, external calls, etc. take time. We can let the server do it later by using queues leading to the better User experience.

like image 26
Gaurav Avatar answered Nov 12 '22 12:11

Gaurav