Adding a new method to a Laravel vendor class

Viewed 65

I'm fairly new to Laravel and I want to add a method to a vendor class. I'm sure it's just my unfamiliarity with how Laravel works, so I'm hoping there's a pretty easy solution.

I've installed a package (https://github.com/kawax/laravel-amazon-product-api) and want to add a new method that I can call like:

use App\Repositories\AmazonSearch\AmazonSearch;

$response = AmazonSearch::alter('All');

So I created a new folder app/Repositories/AmazonSearch and extended the AmazonClient class:

<?php

namespace App\Repositories\AmazonSearch;

use Revolution\Amazon\ProductAdvertising\AmazonClient;


class AmazonSearch extends AmazonClient {
    
    /**
     * {@inheritdoc}
     */
    public function alter(...)
...
}

I guess I'm not sure on exactly what I need to do to be able to have this class instantiated like the original and use this new method.

Should I be creating a new service provider that would instantiate the new class? Can the existing one (https://github.com/kawax/laravel-amazon-product-api/blob/master/src/Providers/AmazonProductServiceProvider.php) just be extended?

There's some other answers here but many of them are for older Laravel versions. I'm not sure how to approach it the Laravel 8 way.

And I'm still fuzzy on how Laravel does all this, so thanks for your patience and any assistance you can provide.

EDIT: Well, I just renamed the class to ExtendedAmazonClient and added a facade and it seems to work now.

namespace App\AmazonSearch;

use Illuminate\Support\Facades\Facade;
use Revolution\Amazon\ProductAdvertising\AmazonClient;


class AmazonSearch extends Facade
{
    /**
     * Get the registered name of the component.
     *
     * @return string
     */
    protected static function getFacadeAccessor()
    {
        return ExtendedAmazonClient::class;
    }
}

trait Alter {
    /**
     * {@inheritdoc}
     */
    public function alter(string $str) {
        dd($str);
    }
}

class ExtendedAmazonClient extends AmazonClient {
    use Alter;
}

Can someone explain to me why the facade was the key?

1 Answers

To answer my own question for anyone else in the future: Facades is another way to use classes without manually creating an object. They are just a shortcut to classes registered by Laravel container.

https://stackoverflow.com/a/48843414/8749507

Related