欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Laravel 類和接口注入相關(guān)的代碼

 更新時間:2019年10月15日 16:56:17   作者:_laomei  
今天小編就為大家分享一篇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)文章

最新評論