Implementing the Adapter Pattern in PHP

Introduction to the Adapter Pattern

In our exploration of Structural Patterns, we’ve seen how they assist in managing object compositions and relationships, facilitating scalable and flexible systems. The Adapter Pattern is similar in that it focuses on enabling two incompatible interfaces to operate together seamlessly.

Consider you have a European plug that you need to use with a U.S. socket. They aren’t inherently compatible, but with the help of an adapter, this gap can be bridged. Similarly, in software design, you’ll often encounter situations where classes need to be integrated despite having incompatible interfaces. The Adapter Pattern offers a solution to achieve this integration.

What You'll Learn

In this lesson, you'll learn how to implement the Adapter Pattern in PHP. We'll begin with a straightforward example where a European plug is connected to a U.S. socket.

The following snippet defines a EuropeanPlug class with an engage method:

PHP
<?php

class EuropeanPlug {
    public function engage() {
        echo "European plug connected.";
    }
}

Next, we have a USPlug interface, which specifies the connect method required by the client:

PHP
interface USPlug {
    public function connect();
}

Finally, here's an Adapter class that adapts the EuropeanPlug to the USPlug interface:

PHP
class Adapter implements USPlug {
    private $plug;

    public function __construct(EuropeanPlug $plug) {
        $this->plug = $plug;
    }

    public function connect() {
        $this->plug->engage();
    }
}

Here's how to interact with these classes:

PHP
$europeanPlug = new EuropeanPlug();
$adapter = new Adapter($europeanPlug);

$adapter->connect(); // Output: European plug connected.

In this example, the EuropeanPlug contains a method engage that we wish to adapt to fit the USPlug interface. The Adapter class serves as the bridge between these two interfaces by implementing the USPlug interface and delegating calls to the EuropeanPlug object.

Use Cases

The Adapter Pattern is frequently used in software development to integrate incompatible interfaces. Below are some instances where it can be beneficial:

  • Legacy Code Integration: When it's necessary to integrate outdated code with new systems having differing interfaces.
  • Third-Party Library Usage: When a third-party library with an incompatible interface is needed in your application.
  • Cross-Platform Development: When developing applications that run on various platforms with different APIs.
  • Testing: When creating mock objects to test components with differing interfaces is required.
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal