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

Original link:
https://stackoverflow.com/questions/37038830/what-is-the-concept-of-service-container-in-laravel#answer-37039108

Laravel The service container is dependency injection container, also applied registrar

When you create objects by hand, the advantages of using the service vessel are:

Have dependent objects are created when management needs the ability

You specified in the application how the object should be created every time you need to create an instance, you only had to service container, it will put together the necessary dependencies and create problems for you to solve

For example, instead of manually creating the object using the new keyword:

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

You can sign up for a service bound container:

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

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

Create an instance of the service vessel by:

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

Interface binding a specific class

Use Laravel automatic dependency injection, when an interface is required in the application (such as the controller constructor), a concrete service class is instantiated automatically container. Concrete class changes when binding, it will change the specific examples of the application object:

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

Using the service container as a registrar

You can create and store in a container a unique instance, and then get them: using App :: instance method to achieve binding, you can use the container as a registrar.

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

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

//做一些其他事情

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

Finally, it should be noted that the container is in fact a service application object: he inherited from the Container class, method, all containers can be obtained

Guess you like

Origin www.cnblogs.com/luyuqiang/p/translate-what-is-the-concept-of-service-container-in-laravel.html