Laravel Observer Pattern (Events, Listeners, Model Observers) Examples

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] hello guys welcome to another lot of lesson today we are going to learn about the observer design pattern note that the observer pattern is not something specific to laravel it is actually one of the common design patterns out there in the software world software development so what we're going to do is to first understand what the observer pattern is how it works we can also talk about some of the advantages of feed and after that we dive into the code to see how we can different ways we can implement this in a lot of application so what is the observer pattern and how does it work the observer pattern is basically a way to observe the state or monitor the state of your application and take action when the state changes in simpler terms what i have on this screen is a really simplified diagram showing the implementation of how the observer pattern works there are two main parts when we talk about the implementation the first is the entity the entity being observed let's take for instance we are building an invoice management application the entity can be invoiced right so we can observe the state of an invoice for example when invoice is created when invoice is updated deleted that kind of action the entity being observed is known as the subject or observable sometimes also called publisher then we have the other parts of your code which are actually listeners or monetary or monitors that kind of monitoring the state of the entity being observed the state of the observable and whenever that state changes whenever um certain action they are interested in is performed they will they will get notified and respond accordingly by respond i mean they will do whatever they want to do based on the notification they get so for example if this were to be the invoice the observable is the invoice this observable x can be the part of your code that sends notification to the customer saying hey a new invoice has been issued to you right this part of the code this observer y can be the one that notifies the admin saying someone in your business generated an invoice and we might have another one observer z that logs this action in the activity log so how does it work the way it works is action is performed on the observable and the an event is fired right this event can be whatever event that is defined for example new invoice is created these observers are interested in this event that's why they're subscribed to that event they're listening to it so whenever invoice is created the invoice created event is fired and all the observers are notified that a new invoice is created and then they take their corresponding action this is like a high-level summary of how the observer person works now let's talk about some of the benefits the obvious one is that you can see that these parts of your code of your codes are loosely coupled so one of the advantages of the observer pattern is that it supports loose coupling between the different parts of your code another advantage of the observer pattern is that it helps you handle the case where multiple objects depend on a single object on the state of an object as you can see on the screen the observer x observer y observer z or depend or all of them are monitoring the state of the observable now there are other benefits as well as disadvantages of using the observer pattern i will leave that one for you to dig deeper and find out for now let's move over to the code and see how we can implement or how this is implemented in laravel before we dive into the code however i want to first of all point out who this lesson is for this lesson is for anyone who has at least the basic knowledge of laravel right so we are not going to go into what is laravel what is model what is controller that kind of thing with that in mind what i have is a brand new laravel it project right no code written so far the first thing i want to do is um to talk about how we are going to do this what we are going to do is just uh make observer observers to monitor the state of an invoice when invoice is created when invoice is updated that kind of action so it means that we are going to have a model invoice model to work with first let me connect to the database i already created which i called um lara obsar that is the name of my database so you do your own database connection after that we head over to the terminal to make the invoice model artisan make invoice model and we add the m flag so that the migration file is also created for the model now i will head over to the migrations file for the invoices table i will define some columns actually since our focus is on is on the observer pattern we are not trying to create some real invoice application i will just keep this simple right so let the invoice have description this is not just this is not some real invoice app right let me add one more thing here say subtotal and i would like the description to be optional to be knowledgeable all right then i'll head over to the model app models and declare those two fields those two columns mass assignable so i say protected level that should be sub total and description okay and then let me make a controller for for the invoice invoice controller at the same time i would like to make a request class where i will handle the validation so artisan make request for creating invoice i will call that store invoice request and i will make one more for updating invoice so let me call that update invoice request in a controller for the invoice please note that we haven't really got to the gist of the matter which is um the observer pattern this is just some setup that i'm running through at the moment so i'll quickly say public function store and the request we are expecting here is stone invoice request now prefer to call this request is in a similar way for update public function update update invoice request request for now i will just keep this very simple what i will do here is to return invoice create request get the validated um fields the validated input right and [Music] for update i'll leave that as it is now let's let's just go to the validation file come on what's going on here here i'll return through no authentication authorization stuff going on there and for the for the rules the subtota should be required numeric and minimum of zero the description however is notable as we define in the in the table schema so now i have a string i will leave that like that for now i will copy this over to the request class for for updating an invoice just paste this thing here but in addition in addition okay actually i wanted to put the id of the invoice where we want to update but i can use route model binding here too so instead of instead of having that in that validation so the next thing i will have to do is to go to the route 5 and define some endpoints oh this is going to be post post to invoices and what we want to do is to create an invoice so invoice controller class the method is stored as we defined in the controller in a similar way for update you can use patch or put here but i will leave it at at post and what we are expecting based on our route model binding is this invoice right the invoice here so i will also keep the invoice really the update is really simple what i would do is invoice update request validated so this will be our for update i will just return the invoice so note that you if you do return here you get an integer because this method returns an integer okay now let's quickly test this what we have so far before we go into the gist of the matter we go over to postman i already have those two endpoints defined to save us some time i mean in the postman with this just on payload if i go ahead and send what's going on here okay we need to start the server php artisans so we have the server up and running at localhost 8000 i will go ahead and send this again validate nullable does not so we have an error in the in the validation no level this is no level there was a type of day i would try this one more time um says okay we have not run the migration so make a new tab here artisan migrate this creates the migration i'll send one more time now we have created an invoice good let's go ahead to update an invoice the id is one i will go over here based on our definition for the right for updating we pass the id of the invoice in the url which corresponds to this parameter we passed here i'll hit the update unauthorized um unauthorized let me check the update invoice so i'll return through here go ahead and send this one more time okay the same typo i had earlier send one more time and we have we have the update working so now we have to create an update working good that is the basic setup we need before we get into the gist of the method that is the observer pattern implementation then we move on to the gist of the method which is implementing the observer pattern remember that what we are trying to achieve is to fire an event when the state of the entity being observed changes whether it is create update or destroy now that kind of event and the observers get notified of this um state change through the event in order there or in our example we are going to do two different things first using the observer event and the listener pattern and then we talk about model observers the first thing i want to do is to generate an event class that is the event that we fired right so to do that we use artisan command php artisan make event we call this let's say invoice created you can also have for invoice updated deleted that kind of thing invoice created so this is the event we also make a listener or an observer so let me make one php artisan make listener let's code is notify customer of new invoice right so whenever invoice is created we notify the customer hey an invoice has been issued to you and you specify the model that is the the event we defined above so this is invoice created this is not the entity being observed by the event that this observer is subscribing to so go ahead um what did i miss actually what you specify is the event not model the event that this observer is subscribing to so this should be event all right so now we have an observable and one listener actually an event and one listener let's go to the start with the event class the first thing i want to do is to register this to the event and the listener and you do that in the event service provider class so here basically in the listing array you define the relationship between the events and the listeners in our case we say invoice created whenever this event is fired then the listeners in this array should be notified currently we have only one that is notify customer of new invoice right let's go to the to the event class in the event class we this is where we can define the entity being observed in this case our invoice public invoice invoice we do the sensor in the constructor so whenever we dispatch this event we're going to pass this as the parameter we should be made available in the constructor this invoice to be invoice so when we fire this event we pass the invoice as a parameter and this invoice will be dispatched along with the event to the subscribers now let's move over to the one of the subscribers that is the notified customer of new invoice you will notice that based on our artisan command when we define this subscriber it actually passes the the event being subscribed to in the handle method here the way you access the the object is through let's call this invoice of course say event invoice this is how you access the the model that you are observing right so here you can do whatever thing you want to do maybe invoice your service do something i don't know do something whatever you want to do at this point onwards but for simplicity for the purpose of demonstration i will just log this invoice you say invoice to array let me get the name of this class so we know where this is coming from when we add other observers okay so why not give this a try before we move further i will head over to postman once again i'll hit this nothing happened the reason nothing happened is that we did not actually fire the event so we need to go to controller in the controller what i want to do is invoice to be this and then here i want to return invoice but before returning i want to fire that event record dispatch this patch is the static method you call on the event class to dispatch that event and remember that in the constructor we are expecting an invoice right the way this works is that the parameter we pass the dispatch method is made available to the constructor this constructor that is how we get it over there i'll go back to postman hit one more time and this time we get what we dumped in the event class you can see this is coming from notify customer of new invoice the handle method as we have it down here actually not here in the in the subscriber class here so far we have just one listener or one observer but remember that we can have multiple observers so why not we just make one more let's call that notify admin of new invoice right so we head over to to the terminal i will change this i will make another subscriber notify admin of new invoice and both modern option oh the same thing again is not model it is event so both subscribers we subscribe to the same event invoice created now what i want to do is actually to do something similar or copy the whole thing here go over to the notify admin but this time i will just change what i am dumping here so we know where these are coming from right i will just go ahead go to postman let's call this one more time i'll scroll up a bit okay the reason we are not getting the second one that is for the admin is because we did not include that in the array remember that you specify all the observers in this array so notify admin of new invoice has to come here we go back one more time we call this you can see now we get notify customer notified admin according to having multiple observers for one event so this is a quick rundown description of the event and listener implementation that laravel has the next thing we want to do is to look at the model observer let's talk about the model observers so far we have a case whereby a consideration where multiple observers are listening to one event laravel gives us a handy way to manage a case whereby an observable is emitting different events remember that this observable can emit different kind of events for example invoice created as we have seen we can also have invoice updated invoice deleted invoice restored invoice is updating that kind of stuff what if we have um one observer that is interested in multiple events fired by or for the model state right so assuming the admin observer this this observer that notifies the admin is interested in invoice create invoice update invoice delete that is where money observers come in handy we are going to have one observer class that can listen to multiple events from the observable so to do that in laravel what you have to do is to use artisan command php artisan make observer here we give the observer a name invoice observer [Music] and we specify the model to observe the state so the model has to be invoiced of course based on our example if you go to the code you will see a folder a new folder created called observer where is it so this is the class we just generated just take a note take a look that we are observing different states of the same model based on the explanation here the same entity multiple events right we have created updated deleted and so on so what i want to do here is i will just in a similar way dump and i will dump invoice to array once again we show where this is coming from when that model is created similarly i want to do for update this time so whenever the invoice is updated we get the same thing it is as simple as that model observer i will go back here to create an invoice i keep forgetting i keep forgetting i can forget it so we need to register this in the event service provider this time i'll come down to the boot method of the event service provider and we say invoice invoice observed what are we observing invoice observer actually i find this counter intuitive that we are saying invoice observe the observer it would have made more sense when we say invoice observer observed invoice i don't know why exactly it is like this but this is the syntax i will go back one more time hit so you can see this time we get three three things dumped this one is coming from notify admin okay this is coming from notify customer and we are we have invoice observer as well in a similar way for update when we update a model the event um okay the reason is that we did not actually update we didn't change anything so now go ahead so when nothing has changed when you call update nothing happens because obviously nothing has been updated now the event is fired of course in this case only for the modded observer because other listeners are subscribing to create not update the only one that subscribes to update event is the model observer here right okay guys if any of the things we have discussed so far makes sense to you or you think it can make sense to someone out there please help the channel grow by hitting the like button and the subscribe button as well to encourage me to produce more content so more and more people out there can have access to this kind of lessons before we call it a day one thing important one thing very important i need to point out is that you need to visit the official documentation of laravel for events and listeners because there are some nitty nitty-gritty stuff that this lesson doesn't cover things like handling cued events database transactions and those kind of stuff so take your time go through the documentation and see other more in-depth details how to implement the observer pattern until next time bye you
Info
Channel: ZestMade
Views: 265
Rating: undefined out of 5
Keywords: Events, Listeners, Model Observer, Laravel, PHP, Observer Pattern
Id: IfltUlUWGRw
Channel Id: undefined
Length: 31min 8sec (1868 seconds)
Published: Sat Jul 24 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.