假设有一个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');
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