mercredi 4 mai 2016

Injecting Interface on class (Laravel Package)

I'm developing my own L5 package for handling payments. To be able to change the payment gateway in the future, I'm using interfaces.

My interface looks like this:

interface BillerInterface
{
    public function payCash();

    public function payCreditCard();
}

I also have a concrete implementation, which is the desired payment gateway.

class Paypal implements BillerInterface
{
    public function payCash()
    {
        // Logic
    }

    public function payCreditCard()
    {
        // Logic
    }
}

The Biller class is the main class, and the constructor method expects the above interface, like so:

class Biller {

    protected $gateway;

    public function __construct(BillerInterface $gateway)
    {

        $this->gateway = $gateway;
    }

    // Logic

}

Last, I created the service provider, to bind the interface to the gateway class.

public function register()
{
    $this->app->bind(BillerInterface::class, 'Vendor\Biller\Gateways\Paypal');
}

Seems to be working, but I'm getting an error when trying to instantiate the Biller class...

Biller::__construct() must be an instance of Vendor\Biller\Contracts\BillerInterface, none given

I tried the following code but doesn't seem to work...

public function register()
{
    $this->app->bind(BillerInterface::class, 'Vendor\Biller\Gateways\Paypal');

    $this->app->bind(Biller::class, function ($app) {
        return new Biller($app->make(BillerInterface::class));
    });
}

Any clues?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/23q4PR1
via IFTTT

Aucun commentaire:

Enregistrer un commentaire