Need to understand laravel service container and service provider through example .. Thanks in advance
问题:
回答1:
Service container is where your services are registered.
Service providers provide services by adding them to the container.
By reference of Laracast. Watch out to get understand.
Service container: https://laracasts.com/series/laravel-from-scratch-2017/episodes/24
Service providers: https://laracasts.com/series/laravel-from-scratch-2017/episodes/25
回答2:
Hello and welcome to stackoverflow!
Service container is the place our application bindings
are stored. And the service providers are the classes where we register our bindings to service container. In older releases of Laravel, we didn't have these providers and people were always asking where to put the bindings. And the answer was confusing. "Where it makes the most sense."! Then, Laravel introduced these service providers and Providers directory to clear things up for people.
To make it easy to understand, I will include a basic example:
interface AcmeInterface {
public function sayHi();
}
class AcmeImplementation implements AcmeInterface {
public function sayHi() {
echo 'Hi!';
}
}
// Service Container
$app = new \Illuminate\Database\Container;
// Some required stuff that are also service providing lines
// for app config and app itself.
$app->singleton('app', 'Illuminate\Container\Container');
$app->singleton('config', 'Illuminate\Config\Repository');
// Our Example Service Provider
$app->bind(AcmeInterface::class, AcmeImplementation::class);
// Example Usage:
$implementation = $app->make(AcmeInterface::class);
$implementation->sayHi();
As you see;
- First we create the container (In real life, Laravel does this for us inside
bootstrap/app.php
), - Then we register our service (inside our Service Provider classes, and
config/app.php
), - and finally, we get and use our registered service. (inside controllers, models, services..)