Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Romain's avatar
Level 30

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.

0 likes
3 replies
Romain's avatar
Level 30

Hello @deringer

I can consider this yes. Where should I actually place that code? Is there a specific file for this or plain and simple in the controller needing it?

thanks.

michaeldyrynda's avatar

The contextual bindings will go into your service provider. Then, depending on the controller, when it asks for a given interface, the service container will inject a concrete implementation based on the configured bindings at run time.

Please or to participate in this conversation.