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

devonblzx's avatar

Polymorphism: selection at run time

So I understand and utilize polymorphism quite a bit with Laravel, however, I'm a little unsure if I'm thinking about selecting services at run time correctly.

On an application level, polymorphism is easy, you bind the class you want to use to the IoC. However, what about on a user level? Let's say I had two payment gateways, paypal and stripe. One user wants their gateway to be paypal, the other wants stripe. I have the two classes StripePaymentMethod and PaypalPaymentMethod implementing a common interface, but what's the proper way of selecting and using these at run time?

Obviously this is going to be opinion based, but I'd like to hear ways people handle this.

My idea consists of creating a selector class named PaymentMethodSelector that accepts the user object and returns the necessary class.

A simplified version being:

class PaymentMethodSelector {

        /**
        * @return PaymentMethodInterface
        */
    public function selectFrom($user) {
              if ($user->gateway == "paypal") return new PaypalPaymentMethod;
              else return new StripePaymentMethod;
        }
}

Then in the controller, I can inject the selector and utilize this like so:

$method = $selector->selectFrom(Auth::user());
$method->acceptPayment();

I'd like to hear your thoughts and critique. Am I missing something? Is there room for improvement?

0 likes
0 replies

Please or to participate in this conversation.