Laravel中服務(wù)提供者到容器的使用是一個非常核心的概念應(yīng)用, 給一個實際應(yīng)用實例方便大家理解學(xué)習(xí)
實例過程簡介:
1. 定義接口名稱 GobjContract [去北京]
2. 實現(xiàn)接口的兩個方法 WalkbjService [步行去北京], TrainbjService[搭火車去北京], 當(dāng)然, 還可以有好多種實現(xiàn)了
3. 服務(wù)提供者注冊, 注冊去北京的方法, 注冊哪個方法, 在應(yīng)用中 依賴注入時, 就會使用哪種方法[這個是 服務(wù)提供者的 主要用途]
注意: 如果是單獨的一個實例, 沒有應(yīng)用 契約[PHP接口], 就沒有必要使用服務(wù)提供者了[Laravel本身支持自動加載注入]
實現(xiàn)步驟如下:
第一步: 定義去北京的接口
namespace App\Contracts; //去北京的接口 interface GobjContract { public function howTo(); }第二步:定義實現(xiàn)去北京的方法:
1>
namespace App\Services; use App\Contracts\GobjContract; //步行去北京 class WalkbjService implements GobjContract { public function howTo(){ echo "我要步行去北京"; } }2>
namespace App\Services; use App\Contracts\GobjContract; //步行去北京 class TrainbjService implements GobjContract { public function howTo(){ echo "我要乘火車去北京"; } }第三步: 實現(xiàn)服務(wù)提供者 php artisan make:provider GobjServiceProvider
namespace App\Providers; use Illuminate\Support\ServiceProvider; use App\Services\WalkbjService; use App\Services\TrainbjService; class GobjServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * @return void */ public function boot() { } /** * Register the application services. * @return void */ public function register() { //綁定去北京的方法為步行 $this->app->bind('App\Contracts\GobjContract',function(){ return new WalkbjService(); }); //綁定去北京的方法為乘火車 /*$this->app->bind('App\Contracts\GobjContract',function(){ return new TrainbjService(); });*/ } }
第四步:注冊服務(wù)提供者到容器 App\Providers\GobjServiceProvider::class
第五步:配置路由: Route::resource('gobj','GobjController');
第六步: 創(chuàng)建控制器: php artisan make:controller GobjController
namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use App; use App\Contracts\GobjContract; class GobjController extends Controller { // protected $gobj; public function __construct(GobjContract $gobj) { $this -> gobj = $gobj; } public function index() { $this -> gobj -> howTo(); //服務(wù)提供者綁定步行: 這里輸出結(jié)果為步行 //服務(wù)提供者綁定乘火車:這里輸出結(jié)果為 乘火車 } }
現(xiàn)在可以通過瀏覽器進行訪問了:http://laravel.cn/gobj