How to extend vendor package service provider in L

2020-02-23 04:18发布

问题:

I am using a package that integrates Xero accounting.

They have a file called XeroServiceProvider.php in the following location: /vendor/drawmyattention/xerolaravel/Providers/XeroServiceProvider.php.

I need to extend this service provider in my application but I don't like the idea of editing this file directly.

Is there a way I can extend this service provider easily without updating vendor files?

Here is the file I need to extend:

namespace DrawMyAttention\XeroLaravel\Providers;

use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Support\ServiceProvider;
use \App\Invoice;

class XeroServiceProvider extends ServiceProvider
{
    private $config = 'xero/config.php';

    public function boot()
    {
        $this->publishes([
            __DIR__.'/../config.php' => config_path($this->config),
        ]);
    }

    /**
     * Register the service provider.
     *
     * @return void
     */
    public function register()
    {
        $this->app->bind('XeroInvoice', function(){
           //return new \XeroPHP\Models\Accounting\Invoice();
           return new Invoice();
        });

    }
}

回答1:

Run php artisan make:provider ExtendedXeroServiceProvider

Add it to ./config/app.php under providers

Open ./app/Providers/ExtendedXeroServiceProvider.php

Change extends ServiceProvider to extends XeroServiceProvider

Add use DrawMyAttention\XeroLaravel\Providers\XeroServiceProvider to it as well

Add the original service provider to the discovery blacklist in ./composer.json

EDIT

as of the time of writing, the drawmyattention/xerolaravel package does not use autodiscovery, but in the event that it does, this can be added to the composer.json:

"extra": {
    "laravel": {
        "dont-discover": [
            "DrawMyAttention\\XeroLaravel\\Providers\\XeroServiceProvider"
        ]
    }
},