简体   繁体   中英

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.

My idea was to create a new class extending the 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:

    $loader = AliasLoader::getInstance();

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

I already tried the boot method too, doesn't work too. What's the best way to override the 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. Under your register function in AppServiceProvider, replace yours with the sample code below. 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 ). Register this facade in config/app.php after the service provider of package:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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