How to use Laravel's bind and singleton methods

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey everyone Andrew here after having my use of singleton pointed out as unnecessary in one of my previous videos I wanted to do some more digging and create a video showing what exactly that method and the related bind method are used for in laravel applications if we take a look at the larval documentation bines are registered using the bind method the first argument that we pass in is a class name followed by a closure that returns an instance of that class we're essentially telling laravel keep this class handy and whenever I reference it I wanted to automatically be initialized with any configuration that I pass in here Singleton's work the exact same way with the same arguments however they have the distinct difference of returning whatever object was created with the first call each subsequent call this is regardless of wherever that call was made from in your code let's get started and see how this works I have here a brand new and blank laravel project it was brought up using my docker compose configuration instead of creating a controller we're just gonna demo this right in the route closure return for our little example let's create a class called external API helper under a helpers directory in our app folder we can assume that in a production application this might be a file that exposes multiple methods for interacting with a third-party services API or something along those lines add in our namespace and add in our class name and let's initialize this with a single simple method called foo and that will return a string with a value of just bar if we navigate back to our web file we can call this class like any typical PHP method first we initialize it with a new keyword and then return the value of the method foo navigating to our app in the browser and refreshing we see that bar is returned just as expected now let's add a bit more complexity to this external API helper class well add in a private variable to store the value of foo and set that value in a constructor instead of hard-coding in the return value of the Foo method we'll return whatever is set in that variable redirecting our application and the browser kicks back in error because we're missing that initial value when we instantiate our class let's go back and add in a hello world refreshing we see our value now this definitely works and it isn't that complex however my goal here is to simplify this down and create a one-liner that can be called statically which honestly looks more laravel like if we open up our app service provider we're presented with two methods by default register and boot we're gonna be focusing on the first one as any binds or registrations that need to be made to the service container for our app have to go in here binding is easily made by calling the bind method through the app service container conveniently held at this app as we saw earlier the first method is the class name which we'll be pulling through with the static class keyword followed by that is our closure which we're going to use to return a new instance of our class that was initialized with a Hello app string back on our web route again we can replace these two lines with a single one-liner the app method is a short call to our application service provider and inside of which we're gonna pass in our class name since this returns an initialized object of our class we can then chain the Foo method right to the end of it refreshing our browser yet again we see the hello app string returned just as expected earlier we talked about wanting to use a larva like static one-liner to call this method and there's a pretty simple way to accomplish this let's go back to our external API helper class and add in a new static method called bar this method returns the call that we made in a web route external API helper class and foo if we then go back to our web rattle and replace that line with external API helper colon colon bar save and refresh our browser we get back the same value as before from a cleaner shorter line okay let's add even more complexity to this class let's create another static method called set foo with a single parameter called foo let's get our class object by calling the app method and we're gonna set the private foo variable using the argument passed in whenever this method is called then let's return the whole object back on our web route we can directly call that set foo method without having to initialize the object we can pass in the string that we want and then call the food method on that object we could honestly even shorten this down further and chain foo on the end of that first line if we wanted to back to the browser we can see that again the string we wanted is displaying as expected so now is the perfect time to look at the difference between bind and singleton let's remove the return and call a second external API helper set foo method passing in a different string than the first will return the values from the Foo method on both of these objects and separate it out by a dash all right let's see what that returns all right after refreshing the browser we can see that we have our two distinct strings that we passed in and returned from our objects the reason for this is that each variable has its own external API helper object and is storing and referencing its own full you let's go back into the app service provider and change the bind call to singleton keeping everything else the same if we refresh the browser now both return strings are exactly the same the last value that was passed in our code Singleton's are a coding pattern in PHP where after initializing a class for the first time you return back the same reference to that class on any subsequent calls instead of initializing another class object so in our code when we use set foo and the first object and then on the next object we're actually running set foo on the same object just stored in two separate variables why would we use Singleton's why would we want the same class returned throughout our code a perfect use case for this pattern is something like an application logger we have a class that gets data pass into it and then determines what to do with that information it could store locally as a flat text file or send it off to a third party bug reporting app regardless of the intention after the logger has been initialized we wouldn't need to or want to for that matter reference more than one instance of that object if during our codes execution logger is needed five different times not using Singleton's would result in calling five different instances of the logger object unless you're destroying them after each successful log event that just takes a valuable memory and can lead to Messier code using a singleton ensures that only one object of that class is initialized at a time throughout our applications execution another great example is for databases we wouldn't want to initialize a database class object with login credentials of multiple times through multiple different classes when we could just reference a singleton instance I hope you've learned as much from this video as I did putting it together and are confident enough to start using bind and singleton service provider methods in your own laravel applications as always if you have any questions please don't hesitate to reach out in the comments below or on my Twitter linked in the description thanks for watching
Info
Channel: Andrew Schmelyun
Views: 12,370
Rating: undefined out of 5
Keywords: laravel, laravel tutorials, web development tutorials, php, php tutorials, service provider
Id: yg1qOom6YuE
Channel Id: undefined
Length: 9min 39sec (579 seconds)
Published: Mon Nov 25 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.