Service Container in Laravel
The Service Container is a dependency injection container and a registry for application. Instead of creating objects manually the benefits of using Service Container are:
It has the capacity to manage class dependencies.
In the application you define how an an object should be created and every time an instance need to be created you ask the service container to do it with the required dependencies.
Another advantage is the binding of interfaces to concrete classes.
When an interface is required in a part of the application, the service container instantiates a concrete class automatically. Changing this concrete class on the binding will change the concrete objects instantiated through all your app.
//everytime a UserRepositoryInterface is requested, create an EloquentUserRepository
App::bind( UserRepositoryInterface::class, EloquentUserRepository::class );
//from now on, create a TestUserRepository
App::bind( UserRepositoryInterface::class, TestUserRepository::class );
Service container can be used as registry.
You can create unique object instances and store them on the container and get them later using App::instance method.
// Create an instance.
$kevin = new User('Kevin');
// Bind it to the service container.
App::instance('the-user', $kevin);
// ...somewhere and/or in another class...
// Get back the instance
$kevin = App::make('the-user');
Comments
0 comments
Please Sign in or Create an account to Post Comments