php容器概念,php-Laravel中服务容器的概念是什么?

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类,获得了容器的所有功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值