Original link: learnku.com/laravel/t/4… For discussion, head to the professional Laravel developer forum: learnku.com/Laravel
Before we can understand a service container, we need to know what a container is. The name explains it all, because a container is where we store things and get them when we need them. Here is a code example.
class container{
public $bindings= []; publicfunction 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')); / / output'Football'
Copy the code
As you can see, I created a container class with two methods
- Bind
- Make
Register our function in a container in the bind method, and then call it in the make method. This is the basic concept of a service container in Laravel
As you’ve read through the Laravel documentation, the Service Container helps us manage dependencies. Let’s look at an example
app()->bind('Game'.function() {return new Game();
});
dd(app()->make('Game')); // Output Game{} // classCopy the code
In the code above app()->bind() binds our service. We can then call the make() method to use it, and we can output it as a class. But if the class Game depends on the class Football, the code below looks like this. It will have an error thrown
Class Game{
public function __construct(Football $football) {$this->football =$football;
}
}
app()->bind('Game'.function() {return new Game();
});
dd(app()->make('Game')); / / outputCopy the code
An error message of class Football not found will be thrown, so we will create a football class, as shown in the code below.
class Football{
}
Class Game{
public function __construct(Football $football) {$this->football =$football;
}
}
app()->bind('Game'.function() {return new Game(new Football);
});
Copy the code
However, if the class Football needs to rely on a stadium class and so on, Laravel can handle the dependencies through the service container.
class Football{
}
class Game{
public function __construct(Football $football) {$this->football =$football;
}
}
/*app()->bind('Game'.function() {returnnew Game(new Football); }); */ dd(resolve('Game')); // output Game{football {}}Copy the code
Therefore, we can say that Service Container is a powerful tool for managing class dependencies and performing dependency injection… 🙂
Original link: learnku.com/laravel/t/4… For discussion, head to the professional Laravel developer forum: learnku.com/Larav