- ServiceContainer 實現(xiàn)Contracts,具體的邏輯實現(xiàn).
- ServiceProvider ServiceContainer的服務提供者珊肃,返回ServiceContainer的實例化,供其他地方使用扇苞,可以把 它加入到app/config的provider中竞滓,會被自動注冊到容器中.
- Facades 簡化ServiceProvider的調(diào)用方式鸵荠,而且可以靜態(tài)調(diào)用ServiceContainer中的方法.
實現(xiàn)
定義一個ServiceContainer,實現(xiàn)具體的功能
namespace App\Services;
class TestService {
public function teststh($data){
return 'dabiaoge'.$data;
}
}
定義一個ServiceProvider供其他地方使用ServiceContainer
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
class TestServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
//
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//單例綁定
$this->app->singleton('Test',function(){
return new \App\Services\TestService();
});
//也可以這樣綁定额港,需要先use App样屠;
App::singleton('Test',function(){
return new \App\Services\TestService();
});
}
在app/config.php中的providers數(shù)組中加入ServiceProvider,讓系統(tǒng)自動注冊.
App\Providers\TestServiceProvider::class,
這時候就可以使用了
use App;
public function all( Request $request){
$a='666';
$test=App::make('Test');//
echo $test->teststh($a);
這樣太麻煩,還需要用make來獲取對象哀托,為了簡便惦辛,就可以使用門面功能,定義門面TestFacade
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class TestFacade extends Facade
{
protected static function getFacadeAccessor()
{
//這里返回的是ServiceProvider中注冊時,定義的字符串
return 'Test';
}
}
在控制器里就可以直接調(diào)用了
use App\Facades\TestFacade;
public function all()
{
$a='666';
//從系統(tǒng)容器中獲取實例化對象
$test=App::make('Test');
echo $test->teststh($a);
//或者使用門面
echo TestFacade::test($a);
}
【轉自 https://segmentfault.com/a/1190000004965752】