DEV Community

Prathamesh Patil
Prathamesh Patil

Posted on • Updated on

Service Container in Laravel

Before Understanding Service container we will know what is a container as a name explain it all as Container is places where we store something and we get it from there when we need it.Below is an example of the code.

class container{

    public $bindings =[];

    public function bind($name, Callable $resource){

       $this->bindings[$name]=resource;

    }

    public function make($name){

       $this->bindings[$name]();

    }


}

$container = new container();

$container->bind('Game',function(){
    return 'Football';
});

print_r($container->make('Game'));

//Out Put

'Football'

Enter fullscreen mode Exit fullscreen mode

As you can see I have created a container class where I have two methods

1)Bind
2)Make

Bind methods register our function in a container and after that, we make use of that function with make function.
This is a basic concept which laravel uses in Service Container

As we have read the laravel documentation, Service Container helps is managing the Dependency. lets see with an example


app()->bind('Game',function(){

    return new Game();

});

dd(app()->make('Game'));

//Output

Game{}  // class 

Enter fullscreen mode Exit fullscreen mode

In Above code with app()->bind() are binding our service to use it .. then we call to make() to use it then we could see an output as a class .. but what if class Game has a dependency on class Football as shown in below code. it will throw an error


Class Game{

public function __construct(Football $football){

$this->football =$football;

}
}

app()->bind('Game',function(){

    return new Game();

});

dd(app()->make('Game'));

//Output

Enter fullscreen mode Exit fullscreen mode

will throw error class football not found so we create a football class as in the below code.


class Football{



}

Class Game{

public function __construct(Football $football){

$this->football =$football;

}
}

app()->bind('Game',function(){

    return new Game(new Football);

});

Enter fullscreen mode Exit fullscreen mode

But What if Football Class has one more dependency of the stadium and so on there laravel handles all through service container.


class Football{



}

class Game{

public function __construct(Football $football){

$this->football =$football;

}
}

/*app()->bind('Game',function(){

    return new Game(new Football);
});*/

dd(resolve('Game'));

//Output

Game{
  football {}
}

Enter fullscreen mode Exit fullscreen mode

So finally we can say that yes service container is a powerful tool for managing class dependencies and performing dependency injection ... :)

Top comments (0)