溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Laravel類和接口注入的實例代碼

發(fā)布時間:2021-09-04 11:10:00 來源:億速云 閱讀:134 作者:chen 欄目:開發(fā)技術(shù)

這篇文章主要講解了“Laravel類和接口注入的實例代碼”,文中的講解內(nèi)容簡單清晰,易于學(xué)習(xí)與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“Laravel類和接口注入的實例代碼”吧!

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類和接口注入的實例代碼”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對Laravel類和接口注入的實例代碼這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關(guān)知識點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI