laravel花式绑定IOC容器

本文介绍如何在Laravel框架中使用服务容器绑定服务,并通过依赖注入的方式使用这些服务。文章详细解释了两种绑定方法:singleton绑定单例和服务容器绑定,以及bind绑定实例到接口以便依赖注入。

假设有一个TestServicer 服务类,声明 一个callme方法。我们想在其他类里面很方便的使用,而不是new。

 

首先创建TestServiceProvider 服务提供者,在这里进行注册TestServicer 服务,

在register中注册,两种方法注册

 

[php]  view plain  copy
 

  1. //使用singleton绑定单例 服务容器绑定  
  2.         $this->app->singleton('test',function(){  
  3.             return new TestService();  
  4.         });  
  5.   
  6.         //使用bind绑定实例到接口以便依赖注入  construct 方法中  
  7.         $this->app->bind('App\Contracts\TestContract',function(){  
  8.             return new TestService();  
  9.         });  
  10.   
  11. //         可以使用bind 123 和服务  ,也可以绑定接口以便依赖注入  
  12.           $this->app->bind('ABC',function(){  
  13.              return new ABC();  
  14.          });  


绑定完了,去config/app.php的providers中添加 服务提供者

 

 

 

[php]  view plain  copy
 

  1. App\Providers\TestServiceProvider::class,  

 

 

这样就完成了注册,可以在其他地方使用了,
1 如本例中 singleton绑定test到服务容器,就可以用

 

[php]  view plain  copy
 

  1. //从容器中解析对象  
  2.          $test =App::make('test');  
  3.         $test->callMe('123');  

 

 

2 bind绑定实例可以方便依赖注入

 

[php]  view plain  copy
 

  1. use App\Contracts\TestContract;  
  2. // 依赖注入  
  3.   public function __construct(TestContract $test){  
  4.         $this->test = $test;  
  5.      }  

$this->test->callMe('TestContract');

 

3 绑定具体的和对应

 

[php]  view plain  copy
 
 
  1. $test = app()->make('ABC');  
  2. $test->callMe('TestController');  




 转载自:http://blog.youkuaiyun.com/qq_28018283/article/details/53392098

参考:http://laravelacademy.org/post/5809.html

推荐参考:https://laravel-china.org/topics/789

转载于:https://www.cnblogs.com/cyforever/p/6139109.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值