DEV Community

Discussion on: Laravel Service Container and Service Providers Explained

Collapse
 
bawa_geek profile image
Lakh Bawa

Thanks, you made it super easy

Collapse
 
fhsinchy profile image
Farhan Hasin Chowdhury

Thanks a lot for letting me know @bawa_geek I almost thought maybe no one's understanding anything 😅

Collapse
 
bawa_geek profile image
Lakh Bawa

your custom Container class made it super clear, however I am trying to understand where we might wan tto use that app()->make(someClass); how can it help.

I use dependency injection already, but not sure how iOC container can help

Thread Thread
 
fhsinchy profile image
Farhan Hasin Chowdhury • Edited

The IoC container helps by performing the instantiation for you.

Assume one of your classes depends on another class and a bunch of other data.

Now every time you want to instantiate an object from that class, you'll have to use new and carefully pass all the parameters.

Assume that one of those dependencies changes during development, now you'll have to painstakingly find all the new statements and update them.

The IoC container allows you to bind a closure that can return an instance of that class. Now anytime you want an object, ask the IoC container. It knows how to make that object. Also if any change occurs, you'll have to change your code in only one place.

Coding with Laravel means coding with elegance. Your code should be functional and beautiful. The auto resolution feature is another example of that. If you type hint your dependencies properly, you won't even have to use app()->make(), saving you some keystrokes and making your code more readable in the process.

There are other benefits regarding testability and stuff but I'll talk about those another day hopefully. Let me know if you've further questions @bawa_geek