契约接口:app\Contracts\LanguageContract.phpphp
<?php namespace App\Contracts; interface LanguageContract { public function speaking(); }
服务类:app\Services\ChineseService.php数组
<?php namespace App\Services; use App\Contracts\LanguageContract; class ChineseService implements LanguageContract { public function speaking() { return '你说的是中文哦'; } }
服务类:app\Services\EnglishService.phpapp
<?php namespace App\Services; use App\Contracts\LanguageContract; class EnglishService implements LanguageContract { public function speaking() { return 'You are speaking English'; } }
服务提供者:app\Providers\TestServiceProvider.phpide
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class TestServiceProvider 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\LanguageContract', 'App\Services\ChineseService'); /** //绑定类名到单例---返回中文--测试可行 $this->app->singleton('chinese', function () { //须要 use App\Services\ChineseService; //控制器中 App::make('chinese') 返回对象 return new ChineseService(); }); */ /** //绑定类名到单例---测试可行,不须要引入服务类了 $this->app->singleton('chinese', function () { return new \App\Services\ChineseService(); }); */ /** //普通绑定类名----测试可行 $this->app->bind('chinese', function () { return new \App\Services\ChineseService(); }); */ /** //绑定类到单例---返回英文---测试可行 $this->app->singleton('english', function () { // use App\Services\EnglishService; //控制器中 App::make('english') 返回对象 return new EnglishService(); }); */ } }
而后在config\app.php中的providers数组中注册该服务测试
控制器测试this
public function c1() { //$test = App::make('chinese'); $test1 = App::make('App\Contracts\LanguageContract'); //$test2 = App::make('english'); var_dump($test1->speaking()); //var_dump($test2->speaking()); }