Laravel Service Container and Service Provider

18.2k Views Asked by At

Need to understand Laravel service container and service provider through an example.

2

There are 2 best solutions below

0
On

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

0
On

The Service container is the place our application bindings are stored. And service providers are the classes where we register our bindings to the service container. In older releases of Laravel, we didn't have these providers and developers 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 the Providers directory to make things more consistent.

Here is 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 can 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, etc.)