Static Methods in Laravel/PHP: When and How?

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello guys today I want to talk to you about static methods in laravel and in PHP in general I received so many questions that I decided to dedicate a video about that and this is a pretty typical example if you have a controller and then you have some kind of service that performs action is it wrong to call that method of that service as a static method without initializing the server itself so you see two examples here with static and without static is static wrong and why and what are good cases to use static methods let's explore in this video so first in this example Property Services just for storing some record the service could be pretty complicated but I simplified that to just one line of creating the property and returning it there will be probably more logic and there are two methods one of them is static and one of them is not static and from a controller also I call it as a static method or non-static method so is it wrong if I do it like this without initializing the service like this the answer is no nothing is wrong if your service class or any class that you call the method from doesn't depend on any other variables doesn't call any more logic from other classes then it's no big deal you just call that class as a helper that helper returns you the result and you move on with your controller so I see a lot of developers saying don't ever use static that is actually not the case for simple examples like this one it's totally fine but things start to get messy with static if the structure of your classes gets more complicated so let's take a look at more examples the next example is a question what if that service class that separate class has some kind of parameters in a Constructor which then participate in that method of store for example our property service belongs to some kind of city and you pass that city as a parameter why while initializing that class of the service so in case of non-static method you just call that as this city name and it works if you try to call that in static method even phpstorm underlines it this method the static method doesn't know anything about this static means that class is not initialized so this would not work in fact you cannot really initialize the service with the Constructor because in this case you're not calling a Constructor we're not doing new Property Service with city name of London we can do that and assign a variable only in case of non-static methods so we initialize the service and then call that in a non-static way like this so this is one limitation of static methods you cannot really initialize its class with parameters another illustration of limitations is what if your method calls more methods internal methods so in the store method if it's not static you can do this and for example for address you need to transform that address into latitude and longitude and you have a private method non-static method then you can call that with this get coordinates you would not be able to do that in static method so this would have the same error as this doesn't exist but there's a workaround to that if you do want to do that then two options either make that method also static which means you can call static get coordinates like this but then that method also needs to be static private static like this or you can skip that static keyword and refer to that method as self get coordinates like this that would also work but those seem to me like a hacky way like a workaround on object-oriented structure because we're calling the methods Without Really initial advising the class that may work but it doesn't feel clean to me I'm just personally not a big fan of that another example and limitation of static methods is what if that method calls another class a method from another class for example that get coordinates by address would be in a separate service let's call it geolocation service and you could initialize that geolocation service from within that method or it's a pretty common practice to have this geolocation service and initialize that service in the Constructor of the class like this with php8 syntax of property promotion in Constructor we could use this geolocation service like this especially if it's used in multiple methods within the same class now if we try to do this geolocation service in the store static method guess what this doesn't work anymore and moreover in that case self wouldn't work either because as you you can see even phpstorm doesn't autocomplete geolocation service it doesn't see that as a variable as a property so self works for internal methods for internal variables but not for something external so in that case if you use static methods you wouldn't be able to initialize the class in the Constructor of the same class another limitation and drawback of static methods in the classes and this is probably the most vocally expressed if you ask a developer about static methods it's not easily testable and markable and if you have an encountered the MOX I have a separate tutorial about mocking services in tests and you will find the link in the text version of this lesson but this is an example for example you want to test that the pose Json for properties works and you also need to test that the service used in that API endpoint actually worked so you mock you kind of fake that service class you initialize that class and you tell that it should receive the call to this method with that parameters the same parameters as here and you test that it's called only once and not twice but also not zero times and in this case if you have static methods you would not be able to get that you will get a testing error that the method is called zero times because in fact that class isn't ever initialized if you call it what static method there are workarounds to that and you can make those tools work but by default in the most typical examples of mocking static methods is a no no so these are the arguments and to summarize when can we use static methods I will show you a few examples in a minute but basically I think you got the vibe that we should use static only if that static method is pretty independent from anything it doesn't call external classes internal methods it doesn't depend and on the class variables or initializing something else I personally like to call static methods helpers which is exactly what they are in most cases and let's take a look at a few examples of that in open source projects the first example comes from a well-known open source project Monica CRM which has date Helper and this is a proof what I told you that static methods are helpers so if you group them into a class around one topic like date for example using static is totally fine so parse date time is a helper to well parse date and time and inside it has internal logic of whether it's carbon or not carbon then it sparse and by the way this is static as well so it caused other static methods from carbon which is also a helper so this static method then is used in a few places in the same project for example in user Factory parse date time in the factory there is no need to initialize helper you just call that that statically in this place and in this place twice or for example in the test parse date time is called like this so this is a classical example of static method as helper another typical example comes from bookstack repository and links to all those repositories by the way are in the text version of this lesson so you can browse around yourself but another example what I wanted to show you is static method within a model or within some class without any other dependencies so default expiry date for API token has this formula and it's kind of like configuration option just not as a static value but rather a method and that method is static and it is called for example in the controller like this API token default expiry or in the Cedar for example like this so in this case static method is kind of like configuration option just expressed in a method because the syntax doesn't allow that to be a constant so you cannot have constant here and assign this formula with using carbon and the third example comes from open source project accounting which is accounting software and this is utility string utility utility is kind of another word for helper in my opinion and in this case the naming isn't really good in my opinion again because it's not Str class it's more initials class so get initials of a person like first name and last name letters from the value of person full name it uses string from laravel under the hood just renamed as I string istr and there's a static method of get initials so you can get initial from one word or from multiple words and these are all static methods within the same class so this is an example of a class which could be one static method just divided into a few kind of helper sub helper methods and then it is used for example in eloquent accessors like this as a static method you could also call that case a helper so this is the overall theme from this video that static methods are great as helpers without external dependencies but if you do have external dependencies or more complicated object-oriented structure be careful when using static methods even if they work now they may be a problem in the future what do you think about this explanation is it clear enough with all those examples or would you add something else shoot in the comments below below this tutorial and let's discuss that's it for this time and see you guys in other videos
Info
Channel: Laravel Daily
Views: 15,841
Rating: undefined out of 5
Keywords:
Id: Ox8dHYRURq8
Channel Id: undefined
Length: 10min 38sec (638 seconds)
Published: Tue Jul 11 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.