Nello Nello - 5 months ago 22
PHP Question

What is the concept of Service Container 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 developer need to know to fully utilize this concept in laravel. Im currently working in laravel 5.2. Anything that would help anyone who is new to laravel to understand this concept would be great.

Answer

The Service Container in Laravel cloud be a Dependency Injection Container and a Registry for the application

Instead of creating objects manually with the new keyword:

$instance = new YourClass();

you can register a binding on the service container:

//add a binding for the class YourClass 
App:bind( YourClass::class, function()
{
    //do some preliminary work;

    return new YourClass();
});

and create an instance through the service container with:

$instance = App::make( YourClass::class );

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

  • Binding of interfaces to concrete classes, so that when a interface is required in your program, 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

  • Possibility to create and store unique intances 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 )