Have you considered contextual binding?
Dynamic Service Bindings
Hi there,
I am starting to build a payment service for my site. Now we want to accept multiple payment methods like Paypal or Stripe. The payment method is selected when the user is at checkout. My question is should I use events to tell the app that the user chose this or that payment method, or should I dynamically bind the proper method in the controller.
So far in my controller, during construction I pass my PaymentMethod interface, and I manually bind the Paypal class in bootstrap/app.php. It works, but I can't really swap. I've been looking for swapping the class dynamically but can't figure out how to do that.
What I have: PaymentMethod interface
<?php namespace SB;
interface PaymentMethod
{
public function buy();
}
Paypal implementation
<?php namespace SB\PaymentMethods;
use SB\PaymentMethod;
class Paypal implements PaymentMethod
{
public function buy()
{
dd('Im buying this!');
}
}
CartController (HTTP controller):
use SB\PaymentMethod;
/**
* @var PaymentMethod
*/
private $payment;
/**
* CartController constructor.
*
* @param PaymentMethod $payment
*/
public function __construct(PaymentMethod $payment)
{
$this->payment = $payment;
}
public function checkout(){
$this->payment->buy();
}
Thanks for any help.
Please or to participate in this conversation.