Laravel 5.7 (Service Container and Service Provider)

放肆的年华 提交于 2019-12-04 18:30:09

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

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..)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!