t0berius
1 month ago
608
15
General

override package method (overriden method not called)

Posted 1 month ago by t0berius

First of all, this is my first try to override a method provided by a package. In detail I try to override this method

Steps I've performed:

1.) Create the required files

App\Http\Helpers\Captcha\CustomCaptchaServiceProvider.php

namespace App\Http\Helpers\Captcha;

use Mews\Captcha\CaptchaServiceProvider;
use App\Http\Helpers\Captcha\CaptchaGenerator;

class CustomCaptchaServiceProvider  extends CaptchaServiceProvider
{

    public function register()
    {
        $this->mergeConfigFrom(
            __DIR__ . '/../config/captcha.php',
            'captcha'
        );

        $this->app->bind('captcha', function ($app) {
            return new CaptchaGenerator(
                $app['Illuminate\Filesystem\Filesystem'],
                $app['Illuminate\Contracts\Config\Repository'],
                $app['Intervention\Image\ImageManager'],
                $app['Illuminate\Session\Store'],
                $app['Illuminate\Hashing\BcryptHasher'],
                $app['Illuminate\Support\Str']
            );
        });
    }
}

App\Http\Helpers\Captcha\CaptchaGenerator.php

namespace App\Http\Helpers\Captcha;

use Mews\Captcha\Captcha;

class CaptchaGenerator extends Captcha
{
    public function create(string $config = 'default', bool $api = false){
        return dd("no!");
    }
}

2.) Now adding my own ServiceProvider inside the AppServiceProvider to make sure my own provider is returned when Mews\Captcha\CaptchaServiceProvider is required:

    $this->app->bind(
        Mews\Captcha\CaptchaServiceProvider::class,
        CustomCaptchaServiceProvider::class
    )

After this I tried to request a captcha using:

{!!Captcha::src()!!}

The captcha is still rendered, my code doesn't get called. Is it correct to override the ServiceProvider?

Where's my fault?

Please sign in or create an account to participate in this conversation.