2

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.

yivi
  • 42,438
  • 18
  • 116
  • 138
Muhaimenul Islam
  • 747
  • 1
  • 7
  • 22
  • 1
    Just pull the class from your database or whatever. It can be a variable: `$class = 'Paypal'; $obj = new $class; $obj->payment($params);` – miken32 Jan 01 '19 at 18:24

1 Answers1

4

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.

casablanca
  • 69,683
  • 7
  • 133
  • 150
  • I totally agree with @casablanca and I'd like to add that would typically have an barrier of abstraction where one (non volatile) side is only depending on abstract types whereas the other (volatile) side is creating the concrete objects. This side is typically related to our Main method. In your case the Factory would belong to the volatile side and could be used through an interface on the non volatile side. – Jan Linxweiler Jan 02 '19 at 11:13
  • Thanks @casablanca. But as I don't have depth knowledge about OOP/SOLID, can you please explain me about how I can use factory object and follow solid? – Muhaimenul Islam Jan 03 '19 at 19:10
  • There are plenty of examples online, just try searching for "php factory pattern". – casablanca Jan 07 '19 at 05:13