StructuralPHPverifiedVerified

Adapter Pattern in PHP

Converts the interface of a class into another interface that clients expect, allowing incompatible interfaces to work together.

How to Implement the Adapter Pattern in PHP

1Step 1: Define the target interface the client expects

interface MediaPlayer
{
    public function play(string $filename): string;
}

2Step 2: Define the incompatible adaptee (legacy)

class LegacyAudioDecoder
{
    public function decodeOgg(string $file): string
    {
        return "Decoded OGG: {$file}";
    }

    public function decodeMp3(string $file): string
    {
        return "Decoded MP3: {$file}";
    }
}

3Step 3: Create the adapter that bridges the interfaces

class AudioPlayerAdapter implements MediaPlayer
{
    public function __construct(
        private readonly LegacyAudioDecoder $decoder,
    ) {}

    public function play(string $filename): string
    {
        $ext = pathinfo($filename, PATHINFO_EXTENSION);

        return match ($ext) {
            'ogg' => $this->decoder->decodeOgg($filename),
            'mp3' => $this->decoder->decodeMp3($filename),
            default => throw new \InvalidArgumentException("Unsupported format: {$ext}"),
        };
    }
}

// Usage
$player = new AudioPlayerAdapter(new LegacyAudioDecoder());
echo $player->play('song.mp3'); // "Decoded MP3: song.mp3"

Adapter Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Adapter Pattern in the Real World

A travel power adapter lets your American laptop plug (client) work in a European wall socket (adaptee) without modifying either. The adapter speaks both “languages”, translating the two-pin plug to the two-round-pin socket, making them interoperable without any changes on either side.