Laravel 類和接口注入相關的代碼
Laravel能夠自動注入需要的依賴,對于自定義的類和接口是有些不同的。
對于類,Laravel可以自動注入,但是接口的話需要創(chuà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'; } }
設置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.
對于接口注入,我們需要在對應的ServiceProvider的register方法中注冊,并將對應的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 類和接口注入相關的代碼就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
ThinkPHP框架整合微信支付之Native 掃碼支付模式一圖文詳解
這篇文章主要介紹了ThinkPHP框架整合微信支付之Native 掃碼支付模式一,結合圖文形式詳細分析了thinkPHP整合微信支付接口的掃碼支付功能相關操作步驟、實現(xiàn)技巧與注意事項,需要的朋友可以參考下2019-04-04