1、创建服务类
Student.php
namespace App\Service\School; class Student { protected $TafficTool; function __construct(WayToSchool $foot) { $this->TafficTool = $foot; } public function goToSchool() { $this->TafficTool->goToSchool(); } }
WayToSchool.php
namespace App\Service\School; interface WayToSchool { public function goToSchool(); }
Foot.php
namespace App\Service\School; class Foot implements WayToSchool { public function goToSchool() { // TODO: Implement goToSchool() method. echo "walk to school"; } }
2、创建service provider
namespace App\Providers; use App\Service\School; use Illuminate\Support\ServiceProvider; class StudentServiceProvider extends ServiceProvider { protected $defer = false; /** * Register services. * * @return void */ public function register() { $this->app->singleton(‘student‘,function(){ return new School\Student(new School\Bike());//不使用WayToSchoolServiceProvider.php 默认的 Foot,实现个性化的需求 }); //$this->app->singleton(‘Student‘,\App\Service\School\Student::class);//使用自动注入解决依赖 } }
WayToSchool.php
namespace App\Providers; use App\Service\School; use Illuminate\Support\ServiceProvider; class WayToSchoolServiceProvider extends ServiceProvider { public function register() { $this->app->singleton(School\WayToSchool::class,‘App\Service\School\Foot‘);//接口 App\Service\School\WayToSchool 默认使用App\Service\School\Foot去实例化 } }
3、写到配置文件 config/app.php 的 providers数组
App\Providers\WayToSchoolServiceProvider::class, App\Providers\StudentServiceProvider::class,
4、使用
routes/web.php
Route::get(‘std‘, function () { app(‘student‘)->goToSchool(); })
输出:by bike to school