haruntunay's avatar

Why do we ever need a Service Container?

I have recently read about Service Containers and Service Providers on laravels docs.

From what i understand, service containers are used to create objects the DI way and service providers are where we register those containers.

But, i can not see any difference between this;

//Bind class to a container.
$this->app->bind(MyClass::class, function ($app) {
    return new MyClass($params);
});

.
.
.
//Make an instance of this class out of that container.
$myObject = $this->app->make(MyClass::class)

and this;

$myObject = new MyClass($params);

Both ways, we get back an instance of MyClass::class with the passed in $params. If so, what was the purpose of all that code we have written to implement a service container ?

0 likes
3 replies
jlrdw's avatar

Well, it's like 6 of one, half a dozen of the other. Same thing.

topvillas's avatar
Level 46

There's many advantages to dependency injection.

If class A depended on class B which depended on class C which depended on class D. Would you really want to track all those dependencies in your code?

If you needed to implement another concrete implementation of an interface. You can change which implementation is used when injecting the interface.

But, in a lot of cases in makes sense to just instantiate the class.

3 likes
ejdelmonico's avatar

https://laravel.com/docs/5.5/container

Scanning the docs through the above link shows the power of using Laravel's Service Container. As stated before, who would want to keep track of dependencies. It all comes down to how large or complicated the app is. Although, why not use something that just works...and works well.

Please or to participate in this conversation.