SOLID Principles in Laravel: 5 Examples (+ New Course!)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys when you take a look at job ads for senior developers laravel and php you see solid principles mentioned quite a lot so this is an example understand solid principles another example of a job ad understanding of refactoring and solid principles and another one a lot of requirements and solid is among them so solid is pretty much a requirement for senior developers but i see a problem that for laravel specifically i don't see many practical examples of how solid should be applied so i decided to shoot this video which actually turned into a full course so like a month ago i started this research on how to sum up the solid in one youtube video and i realized that i cannot do it in one video so i turn it into a course which is now officially released so this video will be a summary of what is essential you need to know about solid principles with examples as i wanted but a short version and if you want to dive deeper with even more examples there's a course on my teachable platform solid code in laravel the link will be in the description below and also i will talk about the scores at the end of this video for now let's go to the basics and let's see what salt actually is and how you can apply it first a bit of a disclaimer when doing the research on solid which started from wikipedia page on the concept itself so there are five principles of solid it's quite opinionated so these are core concepts but they are transformed by various people in different languages in different frameworks in quite a different ways there are people who swear by solid there are people who hate solid there are people in between you may find a lot of different articles on solid on the web so please filter all the information including my own through your lens your situation and apply to your projects now let's get practical the first principle of solid is letter s which is single responsibility principle and this is probably the one that you will use the most because it's the most practical so it says that every entity every class or every method should do only one job or have only one reason to change and probably the best example of that in laravel is bloated controllers and i've been talking about that on this channel multiple times i have a lot of videos on how to refactor controllers into some services or something so let's take a look at another example for example if you have store method which takes care of a lot of things so it takes responsibility for validation then some custom logic of calculating something for example getting the invoice number then actually creating the record which is fine but then creating additional data based on some logic with another loop with another attachment of many-to-many relationships and only then redirect it's too much and i've seen even worse example in my career so this example is totally not the worst so instead of doing all of that in the controller controller should be responsible for well controlling the situation getting the parameters calling whatever methods you want from external classes and then returning the result or redirect so instead of this store method i have another one a better one this store method is doing the same thing but it's much shorter so the validation is in the form request class with the same rules then creation of all the record is in a service called invoice service which also is doing the same thing but in a separate class separation of concerns you just put in the parameters those parameters may be in one array but i've chosen to make them separate so it would be totally clear because that store new invoice may be potentially called not from controller only maybe from unit test or from autism command in the future so you just call the service get the result of invoice which you will use also in the redirect back of which invoice number it is so this is a better controller under single responsibility principle and even if we go one step further inside of that service we can separate the concern of getting the next invoice number so even within the same method or within the same class you can create a separate method or separate class maybe for invoicing of get next invoice number because this method of storing voice is not responsible for getting the invoice number it's kind of against single responsibility principle and having a separate method for that is often better the second principle letter o is open closed principle and it says that the classes or entities should be closed for modification but open for extension what does it actually mean the best example in laravel is packages so whatever is in vendor stays in vendor and you cannot modify that so it's closed for modification but it's open for extension and i will show you an example based on our own package of laravel invoices and all you need to do to generate that invoice you specify the buyer the seller the invoice the invoice items and just call the stream and the result is this invoice the pdf file on the screen but what if we want to change some description for example and add more parameters that packages don't support you cannot edit the package you cannot edit anything in vendor but you can't extend the classes of the package so for example in our package we have a class called invoice item and in invoice item there's a title for example but there's no description what for example if you want to add to that invoice instead of just service one service one and then some description underneath that service one so you would want to have something like invoice item title and some description for example like this you cannot do that directly because the method doesn't exist but you can create your own class and i've done exactly that i just created a class in app classes the folder could be whatever app services app utilities whatever that's your choice it's just important to have the namespace right and then you extend that invoice item class from the package and then you can do whatever in my case i define the description i set the description and then in my main controller instead of doing invoice item i choose invoice item extended like this and i add that to the app classes not sure why my php storm underlines that but it underlies the controller as well so some weird settings are gone but anyway i create an invoice item from my own class which extends the vendor class the package class and then i can use description like this and then i can use that description in the blade file where i show that item and i have that already prepared so item description is available then and then if i refresh that invoice the description is here so this is an example that you create packages which are closed for modification but open for extension and if you create classes not only in packages if you create classes which should not be modified like interfaces for example or some base classes this would be an example of closed for modification but open for extension the third principle letter l is lisk of substitution principle liskov is for surname of barbara liskov who created that principle and it says that the classes should be interchangeable so if you have two classes doing the same thing and implementing the same interface for example you need to be able to safely change one class with another without breaking your application which basically means all the parameters return types and expected exceptions should be identical and let me show you an example so imagine you have employee salary calculator and here i switched to sublime text from phpstorm because storm started to underline some weird stuff and i'm not in the mood to fix that at the moment so let's see how we go with sublime not sure actually is it better or worse shoot in the comments below maybe sublime is better actually to show the code in the future so we have employee all like in any controller then in the employee model you have a calculator of salary with get salary attribute and that calculator is actually depending on the class there is employee type in the database which then forms the class name of salary calculator and then there's a method in designer salary calculator for example calculate and for example hypothetical example of salary depending on just start date of that employee and for example some formula of yearly salary of a designer then another class to calculate that formula for developers or developer salary calculator and those two classes implement the same salary calculator interface which says that every class of that interface should have one method calculate the parameter is start date and the return should be flowed but what if some conditions changed and we want to add some parameter to one of the classes so for example for director salary calculator you need some more parameters like bonus for example this kind of violates the lisk of substitution principle because this class cannot be easily substituted with another class because it has different parameters then so what to do in that case you have a few choices here first choice is to add a default value which means that even if that parameter doesn't exist for other classes it will fall back to default value and will not break the application that's probably the most popular way but if you have some parameter which probably will be needed in the future for other classes you may go to changing the interface if that interface belongs to you so it's not in vendor somewhere you can add that bonus to the interface here as a parameter but then you need to change all the other classes that implement that interface so in designer calculator in developer calculator and all the others even if you don't use that bonus at this time for those classes so that is kind of a big refactoring and it even goes a bit against of all letter of the solid principles so interface should be closed for modification so you need to modify the interface in really edge rare cases in ideal world but we all live in non-ideal world and requirements do change from business point of view so sometimes you need to refactor the class itself and then the interface and then other classes but the best way to describe lisk of principal lisk of substitution principle for laravel is basically use type hints everywhere so you would have the same parameters and you wouldn't be surprised by something like passing string instead of float or the other way around and also the return types of methods are really important so if the return type or parameter type is wrong so php would immediately flag the error and would not allow you to go to the buggy situation so the most practical thing you can learn from it use typings and return types everywhere and use default values for the parameters that maybe not best letter i in the solid principle stands for interface segregation principle or in a more human language interface separation principle and it's used a lot in laravel itself in the framework but i will show you an example from my own demo project in laravel for example you have various classes for various reports of invoices or whatever the example is not really finished it's more like structurally finished so you have report by month and you have report by product report by something else and they all implement report interface report interface has the rule of two methods get the data and download the report right but what if in the future there will be some report that doesn't get downloaded it only gets the data visually then you would be forced to implement that download method even if you don't use it so one of the other definition of that eye letter in the principle that class should not implement the methods that it doesn't need so the typical violation of this eye letter principle interface segregation is interface with too many methods select 10 methods but actually the classes that implements that interface need only like five and the other five would just throw an exception so i've seen people literally doing public function function name and then just throw new exception this method doesn't exist for this case so what if we have something like report by product that only gets the data again not implemented just a structural example but it doesn't get the download method for that you would separate the interfaces so instead of having one report interface you would have separately report data interface with only the getdata method and then report download interface with only the download method and then report by month would implement both of the interfaces like this so instead of implementing report interface you implement comma separated report data interface report download interface and maybe something else and then the other report would implement only the report data interface but not download in laravel core you may see quite a lot of small interfaces with one methods like jsonable html-able and stuff like that and laravel classes or packages classes may implement all of them comma separated or just one or two of them so this is the separation of interfaces and each interface is responsible for their own small set of features and letter d finally is the dependency inversion principle which says that interface should not depend on the concrete implementation or class should not depend on the concrete implementation instead classes should depend on abstractions it actually is hard to understand right but let's take a look at practical example for example you have a controller same scenario report by month and the parameter of that is interface of the report which may be resolved by different classes for example you have a default report by month class which implements that report interface but you may also have some testing report by month class which would implement get data and download in some kind of a different way maybe get data from a different database or from different source maybe download with some fake downloader and not actually download so you have something like this test report by month it's not implemented because it's kind of a structural theoretical example but that class also implements report interface and then in your controller in some situation you want to use the main report in other situations test report for example on local environment or staging or production and then in the controller you pass not the class like report by month something like this but instead you pass the interface and then that interface should be resolved somewhere else for example often case it's an app service provider or another service providers you choose if the environment is local or staging you resolve that report interface with test report by month class with this one otherwise with the main report by month it allows you to not change the main controller if you have some other third class in the future for example you have i don't know sql server report by month if you want to have a different database then you just create that class which implements the same interface so you don't change the controller at all you just add your own class and add that here to the logic of how it would be resolved in what situation that class should be used so after this short or not so short practical overview do you understand those principles better my guess is that for a lot of you all of those interface stuff is quite theoretical and not really applicable in everyday smaller laravel typical projects and you may be right and i would argue personally that you need to know mostly two principles out of those solid and practical everyday life so single responsibility principle it's mostly about bloated controllers two big controllers but not only that if you have two big classes with too many methods or if you have one method with like 100 lines of code it may be separated into different methods and stuff like that this is a really widely used principle of single responsibility and also lisk of substitution principle which in laravel or in php actually comes down to use type hints everywhere and return types everywhere and try to follow your own rules establish the rules of avoiding the surprises in the code what it should be returning in which case all of the other principles are mostly about interfaces which you would be using only if you have certain projects certain project types like bigger projects which would actually have separate implementations of something or if you would create packages or if you would create your own frameworks like laravel so if you need your code to be reusable by someone else and you don't know that someone else how would people as clients as customers would use your code then your code needs to be following all those solid principles with interfaces and strict rules in order not for someone to break that code in their implementation of your interfaces in general salt is not a one time thing that you can apply it's more about way of thinking when coding so when coding you need to constantly ask yourself two questions first question who and how will use that code in the future so imagine yourself in 6 to 12 months imagine your colleague imagine you hire a new developer it may be a junior developer think about who would consume that code in the future and it may be yourself so in your mind talk to that future self and ask if that code will be still readable maintainable and easy to fix the bugs if they appear in that part of the code so that's question one who and how will use that code and question number two what may change in the future it may be changed from another developer or yourself or it may be a business change so for example if you're implementing paypal payments what if in the future you add strap paddle or something like that is it worth to create an interface or not maybe even talk to the stakeholders to the clients what do they expect to happen in the future and then that may affect your current coding structure so second question what may change in the future and finally if we go back to those original job ads that i've shown you in the beginning of this video those job ads talk about solid principles not because you need to apply all those five letters in the code what they mostly expect from you is for your code to be solid to stand the test of time because it's probably the team working on that project the project has a long-term vision so your code should not break like janga tower if something is changed in the future because business requirements change quite often especially in fast growing startups and we have a lot of startups on the market these days they constantly pivot in their direction so your code should be stable but at the same time flexible enough and that is partially described in those solid principles if you want to get even more practical as mentioned in the beginning i had to expand this video into full course which is published now on my teachable platform so here you can see it's solid called in laravel and there are two ways to get the scores first purchase it individually for 29 plus v80 if that's applicable to you or you can purchase yearly membership for all of my 20 courses at the moment and in september i will launch one more with flutter and api so if you want to get all of those it's a better deal in my opinion to get the yearly membership for 99 per year plus vat again now let's briefly take a look what's inside of that course so in addition to explaining all of those letter principles with more examples a few for each letter then we'll take a look at open source repositories where they apply those solid principles also how to make your code solid so this was the video i was preparing for quite a lot of time what are the tools that may help you to test if your code is solid or not or what to refactor i've chosen three tools with three open source projects and i will show you the results in this longer 22 minutes video and then i will touch on some other related principles to solid and also criticism of the solid why solid may be considered as an older approach to the architecture and what are the alternatives so if you want to get deeper the course is on laravel daily.teachable.com here it is as my all other courses and by support those courses you actually support this youtube channel as well because the more courses i sell there the more free time i have to shoot free videos here on youtube and if you want to discuss anything about solid or you want to challenge my opinion on something because again a lot of this stuff is opinionated let's discuss in the comments and see you guys in other videos
Info
Channel: Laravel Daily
Views: 23,493
Rating: undefined out of 5
Keywords:
Id: ZUMQEkoF1_c
Channel Id: undefined
Length: 21min 7sec (1267 seconds)
Published: Mon Aug 30 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.