翻译 What is the concept of Service Container in Laravel?

原文链接:
https://stackoverflow.com/questions/37038830/what-is-the-concept-of-service-container-in-laravel#answer-37039108

Laravel中的服务容器是依赖注入容器,也是应用的注册器

在手工创建对象时,使用服务容器的优势是:

拥有对象创建时管理所需要的依赖的能力

你规定在应用中对象应该如何被创建,每次你需要去创建实例时,你只要管服务容器要,它将一并把必要的依赖问题解决并为你创建

比如,代替手工使用new关键字创建对象:

//每日次我们需要YourClass类时,我们需要手动传入一个依赖
$instance = new YourClass($dependency);

你可以在服务容器中注册一个绑定:

//为YourClass类添加一个绑定
App::bind( YourClass::class, function()
{
    //做一些准备工作:创建一个必要的依赖
    $dependency = new DepClass( config('some.value') );

    //创建并且返回对象的依赖
    return new YourClass( $dependency );
});

通过服务容器创建一个实例:

//没必要去创建YourClass类依赖,服务容器将为我们做!
$instance = App::make( YourClass::class );

接口绑定一个具体的类

使用Laravel自动依赖注入,当一个接口在应用中被需要时(比如在控制器的构造器),一个具体的类被服务容器自动实例化。在绑定时改变具体的类,将会应用中改变具体的实例化对象:

//每一次UserRepositoryInterface接口被请求,将会创建一个EloquentUserRepository类
App::bind( UserRepositoryInterface::class, EloquentUserRepository::class ); 

使用服务容器作为注册器

你可以在容器中创建并储存一个唯一的实例,并且之后获取它们:使用App::instance方法实现绑定,就可以使用容器作为注册器。

//创建一个实例
$kevin = new User('Kevin');

//绑定到服务容器。
App::instance('the-user', $kevin);

//做一些其他事情

//获取对象实例
$kevin = App::make('the-user'); 

最后需要说明的是,实际上服务容器是一个应用对象:他继承自Container类,可以得到所有容器的方法

posted @ 2019-09-12 18:07  luyuqiang  阅读(155)  评论(0编辑  收藏  举报