Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel container and bindings

Laravel 5.6 Documentation says:

There is no need to bind classes into the container if they do not depend on any interfaces. The container does not need to be instructed on how to build these objects, since it can automatically resolve these objects using reflection.

I don't understand it.

Does it mean that I don't have to use any bindigs inside provider's register method if I don't use interfaces?

Then, how can I use dependency injection if I don't use bindigs?

P.S.: in my understending:

"interface" - is this

"bindings" - is bind() and singelton() inside register

like image 209
John Kent Avatar asked May 18 '18 11:05

John Kent


People also ask

What is service container binding in Laravel?

The Laravel service container is a powerful tool for managing class dependencies and performing dependency injection. Dependency injection is a fancy phrase that essentially means this: class dependencies are "injected" into the class via the constructor or, in some cases, "setter" methods.

What is a benefit of Laravel IOC container?

The Laravel inversion of control container is a powerful tool for managing class dependencies. Dependency injection is a method of removing hard-coded class dependencies. Instead, the dependencies are injected at run-time, allowing for greater flexibility as dependency implementations may be swapped easily.

What is a service container and service provider?

Service container is the place our application bindings are stored. And the service providers are the classes where we register our bindings to service container. In older releases of Laravel, we didn't have these providers and people were always asking where to put the bindings.

What is a service container?

A Service Container (or dependency injection container) is simply a PHP object that manages the instantiation of services (i.e. objects). For example, suppose you have a simple PHP class that delivers email messages. Without a service container, you must manually create the object whenever you need it: Copy.


1 Answers

If you have :

class Something {

}

You can do app()->make(Something::class) without needing to bind it before hand. The container knows that it can just call the default constructor.

The same goes for

class SomethingElse {
       public function __construct(Something $s) { }
}   

In this case the constructor will also go through the dependency injection. This is all handled automatically by the container.

However this obviously cannot work for interfaces since interfaces can't be constructed.

Also if you need something to be bound as a singleton you need to bind it explicitly using app()->singleton(...)

like image 138
apokryfos Avatar answered Oct 16 '22 10:10

apokryfos