2
votes

I have multiple types of payment options (Stripe, Paypal, PayUMoney etc.). I want to create seperate class for each payment type and an Payment Interface to be implemented by those classes like this,

interface PaymentInterface {
   public function payment($params);
}
class Stripe implements PaymentInterface {
   public function payment($params) { ... }
}

class Paypal implements PaymentInterface {
   public function payment($params) { ... }
}

From my main class, I want to use a payment method. I will send the payment data to my main method and want to dynamically detect the payment method.

class PaymentModule {
public function confirmPayment(Request $request){
   // create an object of the payment class
   // $obj = new PaymentTypeClass **(Problem is here)**
   // $obj->payment($params)
  }
}

My question is here, how I can dynamically create the related payment class/object and call payment() method from main method?

If I create object conditionally then I am violating Open-Closed principle. Because, I am checking the payment type using If ... else then creating the object and calling the payment() which will may need further modification.

1
Just pull the class from your database or whatever. It can be a variable: $class = 'Paypal'; $obj = new $class; $obj->payment($params); - miken32

1 Answers

4
votes

If I create object conditionally then I am violating Open-Closed principle. Because, I am checking the payment type using If ... else then creating the object and calling the payment() which will may need further modification.

Some piece of your code will eventually have to take user input and decide which payment implementation to use. This is generally done using a factory object, which might use an if-else or a map or some other way of giving you back the correct object, and this is the "single responsibility" of the factory.