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
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.
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.
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.
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.
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(...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With