DEV Community

Debajyoti Das
Debajyoti Das

Posted on

Adapter Design Pattern in PHP

An useful use of interface

The Interface file GatewayInterface.php:

interface PaymentGatewayInterface
{
    public function processPayment(float $amount): bool;
}

class PayPalGateway
{
    public function sendPayment(float $amount): bool
    {
        // Send payment using PayPal API
        return true;
    }
}

class StripeGateway
{
    public function charge(float $amount): bool
    {
        // Charge payment using Stripe API
        return true;
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating StripePaymentAdapter.php:

class PayPalAdapter implements PaymentGatewayInterface
{
    private $payPalGateway;

    public function __construct(PayPalGateway $payPalGateway)
    {
        $this->payPalGateway = $payPalGateway;
    }

    public function processPayment(float $amount): bool
    {
        return $this->payPalGateway->sendPayment($amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

Creating PaypalAdapter.php:

class StripeAdapter implements PaymentGatewayInterface
{
    private $stripeGateway;

    public function __construct(StripeGateway $stripeGateway)
    {
        $this->stripeGateway = $stripeGateway;
    }

    public function processPayment(float $amount): bool
    {
        return $this->stripeGateway->charge($amount);
    }
}
Enter fullscreen mode Exit fullscreen mode

Now multiple type of payments can be done by calling the Interface:

$payPalGateway = new PayPalGateway();
$payPalAdapter = new PayPalAdapter($payPalGateway);
$payPalAdapter->processPayment(100.00); //Here PayPalAdapter's processPayment method is being called

$stripeGateway = new StripeGateway();
$stripeAdapter = new StripeAdapter($stripeGateway);
$stripeAdapter->processPayment(300.00); //Here StripeAdapter's processPayment method is being called
Enter fullscreen mode Exit fullscreen mode

Top comments (0)