mardi 1 janvier 2019

Achieve Open-Closed Principle (SOLID) Using Interface

I am a new learner and trying to use SOLID's Open-Closed Principle in my Project. I have multiple types of payment options (Stripe, Paypal, PayUMoney etc.). So, 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) { ... }
}

now from my main class, I want to use payment method. I will send the payment related datas 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.

Can anyone guide/help me in this regard?

Aucun commentaire:

Enregistrer un commentaire