简体   繁体   English

laravel7 覆盖供应商 package class

[英]laravel7 override vendor package class

I'm new to this service container stuff in general.一般来说,我是这个服务容器的新手。

Just looking for an easy way to override the getView() method of the Captcha class.只是寻找一种简单的方法来覆盖Captcha class 的getView()方法。

My idea was to create a new class extending the captcha class:我的想法是创建一个新的 class 扩展验证captcha class:

<?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...
    }
}

Inside the AppServiceProvider under register method using:register方法下的AppServiceProvider内部使用:

    $loader = AliasLoader::getInstance();

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

I already tried the boot method too, doesn't work too.我也试过boot方法,也不行。 What's the best way to override the class?覆盖 class 的最佳方法是什么? A `serviceProvider' is provided too, but I want to keep things simple and I have no idea about serviceProviders in general.还提供了一个“服务提供者”,但我想让事情变得简单,我对服务提供者一无所知。

You could try this way below to register your service, use bind function instead.您可以在下面尝试这种方式来注册您的服务,使用 bind function 代替。 Under your register function in AppServiceProvider, replace yours with the sample code below.在 AppServiceProvider 中您的register function 下,将您的替换为下面的示例代码。 But please be noticed that first parameter of bind function must be same as facade accessor of vendor library (in this case is \Igoshev\Captcha\Captcha\Captcha::class, you can take a look here ).但请注意,bind function 的第一个参数必须与vendor library 的facade accessor 相同(这里是\Igoshev\Captcha\Captcha\Captcha::class,你可以看这里)。 Register this facade in config/app.php after the service provider of package:在 package 的服务提供者之后,在 config/app.php 中注册这个门面:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM