laravel花式绑定IOC容器

假设有一个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.csdn.net/qq_28018283/article/details/53392098

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

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

posted @ 2016-12-06 21:01  cy成  阅读(843)  评论(0编辑  收藏  举报