09 - Events & Listeners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments

Loving all the content you're producing, Mohamed. I'm really enjoying the streams for the ergodnc app. Thank you for everything.

I didn't know about $dispatchesEvents until this video.

👍︎︎ 8 👤︎︎ u/Charwee 📅︎︎ Sep 21 2021 🗫︎ replies

I love this feature, but I'm also kind of afraid of using it. It's easy to forget about them if you don't work on a project full time, and since listeners can be defined in any ServiceProvider or Model, it can be pretty hard get the big picture. Maybe I've just been overusing (or misusing) them. Has anyone else had the same experience?

👍︎︎ 2 👤︎︎ u/TinyLebowski 📅︎︎ Sep 22 2021 🗫︎ replies
Captions
[Music] a web application may grow to have various aspects and components sometimes you want to decouple these components so they don't depend on each other directly consider a system that has an orders component and a vendors component and vendors need to be notified about new orders that are made by users if you don't want the order component and the vendor component to depend on each other you can register the vendor component as an observer to the changes that happen on the order component this is called the observer pattern and laravel ships with a simple implementation of this pattern that allows you to register events and register listeners to those events events typically live in the app events directory while listeners live in the app listeners directly let me show you what i'm talking about here we are sending a post request to a third party vendor api and another post request to a third party inventory api if you want to convert this piece of code to use the observer pattern we'll need to fire an event once the order is made and register listeners to this event that perform the extra work of communicating with the third party libraries to create an event in laravel we may use the make event arts and command so let's head to the terminal and call php arts and make event and we will call our event order place now if we go back to our ide and check the app events directory we can see the order placed event here now let's create listeners to those events and to create listeners we can use the make listener arts and command so we head back to the terminal and call php arts and make listener and the first listener will be update vendor about order and the event this listener will be listening to is the order placed event now let's go back to our code and move this to the listeners so we will open the app listeners directory and first start with the update vendor about order listener and every listener created will have a constructor and handle method inside the handle method you can put any business logic you want that is related to that listener so we will copy this and paste it here and for this listener to run we need an instance of the order so we can attach this order instance to the event and we will see this shortly for now we will just read the order from the event so event order to array and we will do the same thing in the other listeners so here we copy that and we put it on the other listener inside the handle method and we extract the order from the event instance so event order to array for the sake of this tutorial i'm going to replace the http requests with a simple logging so we can see the listeners running in action so instead of calling http post we are going to use the info helper which will log and align inside our laravel log file so let's log a line that says inventory was updated about order and then print the order id we will do a similar thing inside the other listener but instead of inventory we will call or we will use vendor so one vendor was updated about order and we will print the order id now if we go to the event class the order placed event class we can require the order instance in the constructor so order order and this one will be a public property so now inside the listeners the order instance can be extracted from the event instance let's close this and now we have the listeners created and the event created as well so instead of making the http requests or making the logic for the listeners here we are going to dispatch the order placed event instead by using the dispatch method and any arguments that we pass to the dispatch method laravel will pass these arguments to the constructor of the event so we can pass the order instance here to the dispatch method and laravel will pass it to the constructor of the listener now the only remaining part is that we register the event and its listeners inside the event service provider so let's go to app if app providers event service provider and under the lesson property let's register our event here so order placed class and then we will provide an array of listeners the first listener is update vendor about order and we will provide the class and the second listener is update inventory about order and we are providing the class name as well so now the event is created the listeners are created and they are registered inside the event service provider we are ready to test our code so let's go to the browser and head to our test application so laravel test.test and we can see the view returned here that means the code here ran the order was created and the event was dispatched let's take a look at the log file laravel.log it's under storage logs and we can see the two log lines here vendor was updated about order number four and inventory was updated about order number four and that means the two listeners were triggered when the event was dispatched you can register as many listeners as you want to any event and you can register a listener to multiple events all you have to do is to configure the event service provider and register your events and your listeners now if the event you want to dispatch is related to an eloquent model that's being created updated or deleted you don't have to trigger or you don't have to dispatch those events manually you can configure laravel to dispatch those events for you all you have to do is to define a dispatch events property inside the model class let me show you so we will go to the order model here under ab models order and we will define a dispatch's events property so protected dispatches events and this property expects a value of an array and inside the array we can define the events that we want laravel to dispatch on each eloquent event so what we want to do here is if an order model was created we want to dispatch the order placed event that we created and with only this line added we can remove the manual dispatching that we added here inside the route so we will remove that and let's head to the browser to test our code so i just refreshed if we go to the log file laravel.log we can see that the event was dispatched and the listeners listened for the new order that was created vendor was updated about order number five and inventory was updated about order number five another thing you can also let laravel handle automatically is registering events and listeners instead of you having to register them inside the event service provider and you can enable automatic event discovery by adding a should discover events method inside the event service provider so let's add a should discover events method and return true inside the method body larval finds event listeners by scanning the listener classes it will register the handle method of each listener class as a listener for the event that is type hinted in the method signature and if we take a look at our listeners here we have this event order placed type handed here so when laravel scans this listener it will learn or it will know that this listener listens to this event order placed so let's apply automatic event discovery here since we have it turned on we can remove this from here and the events and listeners will be registered automatically by laravel to test that let's go to the browser and refresh then if we go to the log file we can see the order or the listeners we're triggered by the order number six that we just created when we visited the endpoint in the browser and while automatic event discovery is really nice it's not very efficient for the framework to scan or your listener classes while handling http requests in production to fix that you need to run the event cache arts and command before you deploy your application to production and when this command runs laravel is going to scan all the listener classes and prepare a file that has all the events and the listeners and store it inside your application and laravel will be able to read this file quickly without having to scan all the listener classes so just run the arts and the event cache arts and command before you deploy your application to production and another thing you can do to speed up your application is to send listeners that perform heavy work to the queue let me show you how to do that if the listener contains code that takes time to execute like the listeners that we have here they are supposedly sending an http request to a third party server we can easily send those listeners to the queue by implementing the should queue interface on the listener class so implement should queue and we should do that to the other event as well so implement should queue now laravel will dispatch these listeners to the queue instead of executing the code inside the handle method synchronously the event system in laravel is really powerful and there is more to learn about it in the official laravel documentation so make sure you check it out in the next episode we will look into another great feature of the larval event system which is the ability to broadcast events to front ends so we can deliver real-time updates to our users see you then [Music]
Info
Channel: Laravel
Views: 9,157
Rating: undefined out of 5
Keywords:
Id: K66ulWMj_O0
Channel Id: undefined
Length: 11min 0sec (660 seconds)
Published: Tue Sep 21 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.