Adapter Design Pattern with real-life example in PHP
What is Adapter design pattern?
The adapter pattern is a structural design pattern that allows you to re purpose a class with a different interface, allowing it to be used by a system which uses different calling methods.
When you buy a new phone. Sometimes phones company provide a three-pin charger with the phone. Imagine you have no three-pin socket in your house. What do you do now? Of course, you buy a 2-pin adapter/converter. Now You can easily convert them from 3-pin to 2-pin. That’s called the adapter design pattern. I hope you understand.
Another example with codes
Imagine you work on the shopping cart. Customers can select products and they can select their payment gateway. Now we make a payment process system.
First, we make a common interface for the payment gateway.
Now we implement PaymentGatewayInterface our payment gateway class.
We have another class for the payment process. it’s call PaymentProcessor. PaymentProcessor class has a purchase method. It’s just processing your order.
We have another payment gateway
Stripe . But stripe does not implement PaymentGatewayInterface. stripe class has own
Now issue arise. PaymentProcessor only accept only PaymentGatewayInterface types. This issue easily can solve using an adapter design pattern.
Now we can make an adapter for Stripe. Stripe Adapter implements PaymentGatewayInterface. Under the StripeAdapter class called Stripe makePayment method
Now it’s time to test our codes. It’s working or not
The Paypal class implements PaymentGatewayInterface. But Stripe class does not implement. it has on own method for payment process. For that, we create a middle class that’s called an adapter. This class behind call Stripe makePayment methods. StripeAdapter class is a wrapper for stripe class.
🤗 I hope everyone enjoys it.
🙋 Follow & Subscribe: https://proghasan.medium.com/subscribe