I am starting to look into Laravel but I don't understand the concept of Service Container.
How does it work and what do developers need to know to fully utilize this concept in Laravel?
I am starting to look into Laravel but I don't understand the concept of Service Container.
How does it work and what do developers need to know to fully utilize this concept in Laravel?
The Service Container in Laravel is a Dependency Injection Container and a Registry for the application
The advantages of using a Service Container over creating manually your objects are:
Capacity to manage class dependencies on object creation
You define how a object should be created in one point of the application (the binding) and every time you need to create a new instance, you just ask it to the service container, and it will create it for you, along with the required dependencies
For example, instead of creating objects manually with the
new
keyword:you can register a binding on the Service Container:
and create an instance through the service container with:
Binding of interfaces to concrete classes
With Laravel automatic dependency injection, when an interface is required in some part of the app (i.e. in a controller's constructor), a concrete class is instantiated automatically by the Service Container. Changing the concrete class on the binding, will change the concrete objects instantiated through all your app:
Using the Service Container as a Registry
You can create and store unique object instances on the container and get them back later: using the
App::instance
method to make the binding, and thus using the container as a Registry.As a final note, essentially the Service Container -is- the
Application
object: it extends theContainer
class, getting all the container's funtionalitiesLaravel container create instance for full application from services(class) We don't need to create
instance
for our application likeFirst, We are going look bind static method of
App
class.bind
is just binding your classinstance
(object) with an application, nothing more.Now, we can use this object for our application by using
make
a static method ofApp
class.In above example when we are going to call
make
method then its generate every time newinstance
of class, So Laravel have pretty solution forSingleton
We can bind anobject
to our application bysingleton
method.We can be resolved by
make
method. Now, we have always received the exact same instance from this method.App::instance We can bind an instance to the container and we will always return the exact same instance using
instance
method.We can be resolved by
We can bind interface by
Yaa, We have a question, How can we implement binding in our application? We can implement binding in our
AppServiceProvider