1

I want to switch the payment gateway based on the user's request. I don't want multiple endpoints for each gateway, so i'm trying write one endpoint that handles multiple payment gateways. With that, I also want the controller __construct method to use dependency injection using a gateway interface. The issue i'm running into is switching the instantiated class to match the payment gateway from the request.

use App\PaymentGatewayInterface

class XYZController {
  
  ...

  public __construct(PaymentGatewayInterface $payment_gateway) {
    $this->payment_gateway = $payment_gateway; //This should be a gateway instance of either Paypal, Stripe, Braintree, etc based on the $request of the user.
  }
  
  ...
}

I know I can bind an interface to a class in the register() method of a provider and add some logic there, but I can see myself adding a lot of interface dependencies in the controller actions and I feel that having logic in the service provider can become messy rather quick. Example:

...
class AppServiceProvider extends ServiceProvider
{
  public function register()
  {
    if(request()->input('gateway') === "Paypal")
      $this->app->bind(PaymentGatewayInterface::class, PaypalGateway::class);
    else
      $this->app->bind(PaymentGatewayInterface::class, StripeGateway::class);
  }
}
2
  • Maybe make the dependency a factory? Then create the necessary payment gateway by passing the request's gateway to the factory? Commented Sep 3, 2021 at 17:24
  • 1
    Try creating a proxy implementation for PaymentGatewayInterface that is able to forward the call to one of its PaymentGatewayInterface dependencies. The proxy can make this decision based on (runtime) request data. This way you don't need a factory and XYZController stays oblivious to the fact that there might be more implementations to choose from. If it's impossible for the PaymentGatewayProxy to retrieve this request data, you might be better of with an adapter interface that accepts the gateway type in its method arguments, but still forwards the request to a PaymentGateway. Commented Sep 4, 2021 at 11:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.