I am starting to look into Laravel but I don't understand the concept of Service Container.

它是如何工作的,开发人员需要知道什么才能在Laravel中充分利用这一概念?

推荐答案

Laravel中的Service Container是一个依赖注入容器和应用程序的注册表

The advantages of using a Service Container over creating manually your objects are:

Ability to manage class dependencies on object creation

You define how a object should be created in one point of the application (the binding) and every time you need to create a new instance, you just ask it to the service container, and it will create it for you, along with the required dependencies

For example, instead of creating objects manually with the new keyword:

//every time we need YourClass we should pass the dependency manually
$instance = new YourClass($dependency);

you can register a binding on the Service Container:

//add a binding for the class YourClass 
App::bind( YourClass::class, function()
{
    //do some preliminary work: create the needed dependencies
    $dependency = new DepClass( config('some.value') );

    //create and return the object with his dependencies
    return new YourClass( $dependency );
});

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

//no need to create the YourClass dependencies, the SC will do that for us!
$instance = App::make( YourClass::class );

Binding of interfaces to concrete classes

使用Laravel automatic dependency injection,当应用程序的某些部分(即控制器的构造函数)需要接口时,服务容器会自动实例化一个具体的类.更改绑定上的具体类将更改通过所有应用程序实例化的具体对象:

//everityme a UserRepositoryInterface is requested, create an EloquentUserRepository 
App::bind( UserRepositoryInterface::class, EloquentUserRepository::class ); 

//from now on, create a TestUserRepository 
App::bind( UserRepositoryInterface::class, TestUserRepository::class );

Using the Service Container as a Registry

You can create and store unique object instances on the container and get them back later: using the App::instance method to make the binding, and thus using the container as a Registry.

// Create an instance.
$kevin = new User('Kevin');

// Bind it to the service container.
App::instance('the-user', $kevin);

// ...somewhere and/or in another class...

// Get back the instance
$kevin = App::make('the-user'); 

As a final note, essentially the Service Container -is- the Application object: it extends the Container class, getting all the container's funtionalities

Laravel相关问答推荐

Laravel将变量从模板到已发布的供应商模板

未定义防护 [api] 的授权驱动程序 [api]

如何在 NetBeans 中添加带有点 (blade.php) 的自定义文件扩展名?

克隆后设置 Laravel 项目

Laravel 4:验证前修剪输入的最佳实践

使用 Laravel 限制多态多对多关系中的相关记录

在 laravel 如何将额外的数据传递给 mutators 和 accessors

Heroku 上的 Laravel 队列工作者

localhost 和stream_socket_enable_crypto():SSL 操作失败,代码为 1

如何仅从 laravel FormRequest 中获取经过验证的数据?

如何在 Laravel 中创建类别的嵌套列表?

在 AWS 上找不到 Laravel 5 类Collective\Html\HtmlServiceProvider

Laravel 中的填充方法不起作用?

Laravel 5 与 Postgresql

Laravel Mail 发送Electron邮件但返回 false

在 Laravel 中按用户名查找用户

laravel 队列 - 同步驱动程序如何工作?它是在单独的进程/线程还是主执行线程中执行?

如何以及在哪里可以使用 laravel 存储图像?

如何在 Laravel 5 请求类中使用有时规则

Laravel如何仅响应没有正文消息的204代码状态