Laravel中的服务容器是依赖注入容器和应用程序的注册表
与手动创建对象相比,使用服务容器的优势在于:
管理对象创建上的类依赖性的能力
您定义如何在应用程序的某个位置(绑定)创建对象,并且每次需要创建新实例时,只需将其请求到服务容器,它将为您创建它以及所需的对象 依存关系
例如,不是使用Application关键字手动创建对象:
//every time we need YourClass we should pass the dependency manually
$instance = new YourClass($dependency);
您可以在服务容器上注册绑定:
//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 );
接口与具体类的绑定
使用Laravel自动依赖项注入时,当应用程序的某些部分(即控制器的构造函数)中需要接口时,服务容器会自动实例化一个具体的类。 更改绑定上的具体类,将更改通过所有应用实例化的具体对象:
//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 );
使用服务容器作为注册表
您可以在容器上创建并存储唯一的对象实例,并在以后将它们返回:使用Application方法进行绑定,从而将容器用作注册表。
// 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');
最后一点,实际上,服务容器是2989033965882982967040对象:它扩展了2989033965882982967041类,获得了容器的所有功能