依赖注入其实就是interface在laravel的实现,他不会直接new对象,而是通过传参获取对象的实例。比如经典的例子,超人有超能力,但是超能力有很多,比如火焰、冰霜,直接在超人class里面new火焰超能力,如果要换超能力的话,还得修改超人class的代码,通过interface制定契约就可以避免这种依赖。
举一个支付的例子。
1.支付接口
<?php namespace App\Repository\Interfaces; interface PayMethodInterface{ public function payMoney($money_amount); }
2.阿里支付模块
<?php namespace App\Repository\Repositories; use App\Repository\Interfaces\PayMethodInterface; class AliPay implements PayMethodInterface { public function payMoney($money_amount){ echo 'aliPay'.$money_amount; } }
3.微信支付模块
<?php namespace App\Repository\Repositories; use App\Repository\Interfaces\PayMethodInterface; class WechatPay implements PayMethodInterface { public function PayMoney($money_amount){ echo 'wechat'.$money_amount; } }
4.通过ServiceProvide把Interface和具体支付模块建立联系(bind)
<?php namespace App\Providers; use Illuminate\Support\ServiceProvider; class PayMethodServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // $this->app->bind('App\Repository\Interfaces\PayMethodInterface', 'App\Repository\Repositories\AliPay'); } /** * Bootstrap any application services. * * @return void */ public function boot() { // } }
5.在config/app.php定义新建的ServiceProvider
/* * 自定义接口实现类 */ App\Providers\PayMethodServiceProvider::class,
6.lbbController.php使用依赖注入
<?php namespace App\Http\Controllers; use App\Repository\Interfaces\PayMethodInterface; use Illuminate\Http\Request; class lbbController extends Controller { // protected $payMethod; public function __construct(PayMethodInterface $payMethod) { $this->payMethod = $payMethod; } public function index(){ $this->payMethod->payMoney(100); } }