DEV Community 👩‍💻👨‍💻

Discussion on: Laravel Service Container and Service Providers Explained

fhsinchy profile image
Farhan Hasin Chowdhury Author • Edited on

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