laravel5.3 绑定服务容器例子

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


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

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

//使用singleton绑定单例 服务容器绑定
        $this->app->singleton('test',function(){
            return new TestService();
        });

        //使用bind绑定实例到接口以便依赖注入  construct 方法中
        $this->app->bind('App\Contracts\TestContract',function(){
            return new TestService();
        });

//         可以使用bind 123 和服务  ,也可以绑定接口以便依赖注入
          $this->app->bind('ABC',function(){
             return new ABC();
         });

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


App\Providers\TestServiceProvider::class,


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

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


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

use App\Contracts\TestContract;
// 依赖注入
  public function __construct(TestContract $test){
	 	$this->test = $test;
	 }
$this->test->callMe('TestContract');

3 绑定具体的和对应

 $test = app()->make('ABC');
 $test->callMe('TestController');



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

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值