[Live-Coding] Refactor Laravel Controller to be Much Shorter

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
in this lesson we'll will try to refactor a controller controller method which is pretty big and refactor that into layers of validation services and all of the classes that the code belongs to instead of being it in a controller in other words controller should be shorter and we will have an example of how to shorten one method it's a fictional example I won't even launch that code but we will go step by step and move that go to somewhere else so here we have a typical update method on resourceful controller so we have a post ID we have a request and then we update the post and do some more magic and again example is fictional but pretty typical and pretty close to real life so what we're doing first is we're finding post and if we don't find we abort to 404 first thing we can shorter is do find or fail so that it would be the same thing as doing checking if it's 404 or it exists but even shorter thing we can use route model bindings so instead of post ID we will type in post and do post here and that's it so assuming that you have in your routes in routes web you have route resource and it's resourceful controller then lateral will know that post means you need to find the post object by ID if it's any other field that not ID you can change route model binding and settings off that eloquent model okay so first step done we cannot we don't need to find the post ok that's shorter done validation some people do validation in controller and a big fan of form requests that actually validation belong to somewhere else so let's make a request file and PHP artisan make request of date no post update request okay posted late request we have a new file and posted late request authorized CC safety true and we move both texts required rule to this array and then instead of doing all of that we're doing instead of request we're doing post of date request and then that request file takes care of all the validation you can have more rules here and then we can delete all of that section with validation so if it doesn't if it isn't valid then it will return back with errors and then we can remove this one and remove this one okay shorter already right so then we're doing post update and this is not thing that can be short too much of course you can do more logic you're like request only the fields like post text and something like that but it's pretty typical example of request all being passed to the post so this is okay we're leaving it here because that's the main thing that that update function does it's updating next this part is a fictional example of for example post has several authors with many to many relationship and for all the authors we need to update update the record of words count per author well that's assuming that author table has works count field actually missing one function so something like that and this something tells me that that doesn't belong to this controller it should be somewhere else so some logic some some layer some class that should observe the update functionality and then and then do all that logic so let's create an observer for that you make observer post observer I think it's this look this syntax I'm not mistaking rooms over quite successfully okay so we have AB observers post observer and it works with our post because we specified that and then we can move this to updated so updated event happens and then we have post as a parameter and then we can do the same logic here in observer and we need to register that observer I think it's in service provider or is it in route service provider actually let's Google that that's a beauty of of almost live coding you will see that I don't remember everything by heart I'm googling as any normal human being so observer I have an observer class blah blah blah app service provider we need to match to that so no it's not copy and paste its service phpstorm almost crashed on me now peach peach this so post observe and then class will be post server class yep we've registered it and now it should observe the the post updated method but not even that even this looks a little long-term and even for each doing the posts yeah it doesn't feel right for me it should be a service so a service of functionality in my opinion service is a class that calculates something so in this case it's pretty simple logic but in reality it could be much more complicated so let's create a separate service new directory services then we have a new file let's call it post service PHP and inside of it do a class post service and we can do anything here so function calculate author words for example and author is the parameter and instead of doing that in the observer we do that this one not that part okay so we take it here so for each author posts which are Ward's count this and then instead of doing words count here's a parameter as a variable we will do a service so post one more thing of forgotten namespace services okay and let's assume it's will be a parameter so it be it will be auto loaded here unused parameter so we will do post service calculate author words author so this way we will use two patterns here course parameter is missing baramos service this one so we use two patterns here instead of doing the calculation in a controller it will be caught by observer which in turn use the service to for some calculation again it's a pretty simple example in this example for this project probably I wouldn't use a service for one or two lines of code but you get the point that it does make sense to use that if you have more complicated logic for some calculation it shouldn't be in a controller and it shouldn't even be an observer because observers should be also catching the logic catching the event and loading the logic to somewhere else so okay we've taken care of the update in the statistics some kind of statistics and then final thing is sending an email to administrator that the post was updated so instead of catching this one we will do notification class it's horrible it's artisan made notification post updated notification I'm a big fan of doing suffixes in all the classes that it's not just post up data it's possibly that notification so class name and file name would tell you exactly what it's what it does so to mail instead of that I will do to mail instead of doing this I would do admin so okay this if admin then had been notified and class would be that post updated notification I think it's this syntax since I won't launch this code it's not really important to catch the syntax but let's take a look at and documentation for shoulder communication wearable notifications it's cool to see my own websites and Google search and cook it in the battle anyway notify what's the syntax yeah new invoice based on new class new post update identification and let's say that the parameter will be post and in that class we should have a constructor post post then we should have private or private post then do dependency injection it's not exactly dependency injection but it's rejecting the parameter of our controller by a constructor and then inside of mail message we can use one action for example post was updated updated and have this post the name for example something like that and in a controller we just load the notification to admin and even this can be shortened I think that sending the notification or updating someone it's a job because it could be curable so instead of instead of sending the email and in this case user will actually will actually wait for that email to to be sent we will do a job so office only make job sound post updated job actually yeah well yeah let's call it this way so make job we have the jobs new file send post updated job and handle is this one and let's move all the logic into here so both the big identification should be your now and post as a parameter handle post we will get to that so user should be also in here and post should be a parameter so post should be also in a constructor post post then we have a private variable private post we will solve it here this post equals post and this post is a parameter right so this is good and in a controller all willing to do is dispatch dispatch a job which is new post updated send post a beta jobs job with a parameter post hmm let's double check the syntax again wearable jobs dispatch dispatching jobs dispatch yeah there are there's syntax to dispatch the class like this one yeah but I think dispatch is also batching job yeah of course yeah anyway I think that should work and I guess that said it's not even that actually even this dispatch could be moved to our observer so post observer update this one so we are observing the change calling a job that job could be curable and inside of that job we call the notification class and yeah so look at our controller now we don't need these we don't need these were only anything here so controller method has two lines update the code and redirect back and all the logic is behind the scenes doing the notifications doing the checks during the validation some calculation in service queuing the job to send notification ahead and actually looking for that admin everything is behind the scenes so that is my way in my example to move the logic from the controller shorten the controller to do exactly what it does and then all the logic is in these classes and every every class has its own logic and if you know laravel pretty well you will know where to find it where is the job where is notification where's observer and where is this service so this is the example of refactoring controller into shorter one
Info
Channel: Laravel Daily
Views: 59,983
Rating: undefined out of 5
Keywords: laravel, php
Id: ShrS3HXwzPg
Channel Id: undefined
Length: 14min 55sec (895 seconds)
Published: Mon Feb 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.