- ServiceContainer 實(shí)現(xiàn)Contracts,具體的邏輯實(shí)現(xiàn).
- ServiceProvider ServiceContainer的服務(wù)提供者,返回ServiceContainer的實(shí)例化,供其他地方使用,可以把 它加入到app/config的provider中,會(huì)被自動(dòng)注冊(cè)到容器中.
- Facades 簡(jiǎn)化ServiceProvider的調(diào)用方式,而且可以靜態(tài)調(diào)用ServiceContainer中的方法.
實(shí)現(xiàn)
定義一個(gè)ServiceContainer,實(shí)現(xiàn)具體的功能
namespace App\Services;
class TestService {
public function teststh($data){
return 'dabiaoge'.$data;
}
}
定義一個(gè)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)自動(dòng)注冊(cè).
App\Providers\TestServiceProvider::class,
這時(shí)候就可以使用了
use App;
public function all( Request $request){
$a='666';
$test=App::make('Test');//
echo $test->teststh($a);
這樣太麻煩,還需要用make來獲取對(duì)象,為了簡(jiǎn)便,就可以使用門面功能,定義門面TestFacade
namespace App\Facades;
use Illuminate\Support\Facades\Facade;
class TestFacade extends Facade
{
protected static function getFacadeAccessor()
{
//這里返回的是ServiceProvider中注冊(cè)時(shí),定義的字符串
return 'Test';
}
}
在控制器里就可以直接調(diào)用了
use App\Facades\TestFacade;
public function all()
{
$a='666';
//從系統(tǒng)容器中獲取實(shí)例化對(duì)象
$test=App::make('Test');
echo $test->teststh($a);
//或者使用門面
echo TestFacade::test($a);
}
【轉(zhuǎn)自 https://segmentfault.com/a/1190000004965752】