Example 1

Use case: Create two payment methods - Paypal and Stripe - using the same client API when it comes to payment process given that Paypal and Stripe have different API methods

Let's assume the following implementations of Paypal and Stripe from their creators

<?php

class Paypal
{
    public function sendPayment(int $amount)
    {
        return "Pay $amount with Paypal";
    }
}

 

<?php

class Stripe
{
    public function payAmount(int $amount)
    {
        return "Pay $amount with Stripe";
    }
}

In order of utilising these two differently implemented payment methods using the same API in our app we need to create a common interface for these two so we can use them interchangeably.

Let's say we need something like this

<?php

interface PaymentInterface
{
    public function pay(int $amount);
}

Normally we don't want to edit the source code of Paypal and Stripe because it doesn't belong to us. So we need to create our own adapters for these that adhere to our interface

<?php

class PaypalAdapter implements PaymentInterface
{
    private $paypal;

    public function __construct(Paypal $paypal) // This comes form the original Paypal package
    {
        $this->paypal = $paypal;
    }

    public function pay(int $amount): string
    {
        return $this->paypal->sendPayment($amount);
    }
}

 

<?php

class StripeAdapter implements PaymentInterface
{
    private $stripe;

    public function __construct(Stripe $stripe) // This comes form the original Stripe package
    {

        $this->stripe = $stripe;
    }

    public function pay(int $amount): string
    {
        return $this->stripe->payAmount(22);
    }
}

Now we achieved a common API between these two payment methods for our app even though their payment process is different

<?php

$paypal = new \App\Structural\Adapter\ExampleOne\Paypal();
$payment = new PaypalAdapter($paypal);

$payment->pay(20); // Outputs 'Pay 20 with Paypal'

$stripe = new \App\Structural\Adapter\ExampleOne\Stripe();
$payment = new \App\Structural\Adapter\ExampleOne\StripeAdapter($stripe);

$payment->pay(20); // Outputs 'Pay 20 with Stripe'