Laravel 類和接口注入相關(guān)的代碼
Laravel能夠自動注入需要的依賴,對于自定義的類和接口是有些不同的。
對于類,Laravel可以自動注入,但是接口的話需要創(chuàng)建相應(yīng)的ServiceProvider注冊接口和實現(xiàn)類的綁定,同時需要將ServiceProvider添加到congif/app.php的providers數(shù)組中,這樣容器就能知道你需要注入哪個實現(xiàn)。
現(xiàn)在自定義一個類myClass
namespace App\library;
class myClass { public function show() { echo __FUNCTION__.' Hello World'; } }
設(shè)置route
Route::get('test/ioc', 'TestController@index');
修改TestController
class TestController extends Controller { public function index(myClass $myClass) { $myClass->show(); } }
訪問http://localhost/test/ioc,能成功打印show Hello World。
修改myClass
class myClass implements like { public function play() { // TODO: Implement play() method. echo __FUNCTION__.' Hello Play'; } }
like接口
interface like { public function play(); }
TestController
class TestController extends Controller { public function index(like $like) { $like->play(); } }
如果還是訪問上面的地址,會提示錯誤
Target [App\library\like] is not instantiable.
對于接口注入,我們需要在對應(yīng)的ServiceProvider的register方法中注冊,并將對應(yīng)的ServiceProvider寫入config/app的providers數(shù)組中。
定義LikeServiceProvider
class LikeServiceProvider extends ServiceProvider { public function boot() { // } public function register() { // $this->app->bind('App\library\like', 'App\library\myClass'); } }
之后我們需要將LikeServiceProvider添加到config\app.php文件的providers數(shù)組中。
還是繼續(xù)訪問上述的地址,頁面成功輸出play Hello Play。
以上這篇Laravel 類和接口注入相關(guān)的代碼就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
ThinkPHP框架整合微信支付之Native 掃碼支付模式一圖文詳解
這篇文章主要介紹了ThinkPHP框架整合微信支付之Native 掃碼支付模式一,結(jié)合圖文形式詳細分析了thinkPHP整合微信支付接口的掃碼支付功能相關(guān)操作步驟、實現(xiàn)技巧與注意事項,需要的朋友可以參考下2019-04-04Yii入門教程之目錄結(jié)構(gòu)、入口文件及路由設(shè)置
本文從YII的目錄結(jié)構(gòu)開始分析,到入口文件分析,到路由設(shè)置詳解,視圖詳解,十分全面的向我們展示了YII框架的方方面面,是篇非常不錯的文章,這里推薦給大家。2014-11-11Codeigniter檢測表單post數(shù)據(jù)的方法
這篇文章主要介紹了Codeigniter檢測表單post數(shù)據(jù)的方法,實例分析了Codeigniter獲取及檢測post數(shù)據(jù)的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-03-03