首页 > 解决方案 > laravel7 覆盖供应商包类

问题描述

一般来说,我是这个服务容器的新手。

只是寻找一种简单的方法来覆盖类的getView()方法Captcha

我的想法是创建一个扩展类的新captcha类:

<?php

namespace App\Http\Helpers\Captcha;

use Igoshev\Captcha\Captcha\Storage\StorageInterface;
use Igoshev\Captcha\Captcha\Generator\GeneratorInterface;
use Igoshev\Captcha\Captcha\Code\CodeInterface;

class CaptchaNew extends Igoshev\Captcha\Captcha
{
    /**
     * Get html image tag.
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function getView()
    {
        //new code...
    }
}

AppServiceProvider下面的register方法中使用:

    $loader = AliasLoader::getInstance();

    $loader->alias('App\Http\Helpers\Captcha\CaptchaNew', 'Igoshev\Captcha\Captcha');

这个方法我也试过了boot,还是不行。覆盖类的最佳方法是什么?还提供了一个“服务提供者”,但我想让事情变得简单,我对服务提供者一无所知。

标签: phplaravel-7

解决方案


您可以在下面尝试这种方式来注册您的服务,改用绑定功能。在 AppServiceProvider 中的函数下,将您的register函数替换为下面的示例代码。但请注意,绑定函数的第一个参数必须与供应商库的外观访问器相同(本例为\Igoshev\Captcha\Captcha\Captcha::class,您可以看这里)。在 config/app.php 中注册这个门面在 package 的 service provider 之后:

$this->app->bind(\Igoshev\Captcha\Captcha\Captcha::class, function(){
     return new CaptchaNew($this->app['config']);
})

推荐阅读