laravel依赖注入

1 篇文章 0 订阅
1 篇文章 0 订阅

依赖注入其实就是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);
    }
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值