Application 2019-02-01

Learning Design Patterns with PHP - Adapter Pattern

Master the Adapter pattern to change interfaces without modifying original classes using composition and wrappers in PHP.

Read in: ja
Learning Design Patterns with PHP - Adapter Pattern

Overview

An article that didn't make it in time for the PHP Design Patterns Advent Calendar 2018.

What is the Adapter Pattern?

A pattern that allows you to change the interface without modifying the original class.

It is achieved by preparing an Adapter class that adjusts compatibility between different interfaces.

Implementation

<?php
interface Bird
{
    public function fly();
}

class SmallBird implements Bird
{
    public function fly()
    {
        echo 'fly short time';
    }
}

class BigBird implements Bird
{
    public function fly()
    {
        echo 'fly long time';
    }
}

class Human
{
    public function eat(Bird $bird)
    {
        echo 'Yummy!';
    }
}

class MiddleBird
{
    public function jump()
    {
        echo 'jump like flying';
    }
}

// Adapter
class MiddleBirdAdapter implements Bird
{
    private $middleBird;

    public function __construct(MiddleBird $middleBird)
    {
        $this->middleBird = $middleBird;
    }

    // Wraps the method of MiddleBird
    public function fly()
    {
        $this->middleBird->jump();
    }
}

$human = new Human();

$smallBird = new SmallBird();
$human->eat($smallBird); // Yummy

$middleBird = new MiddleBird();
$middleBirdAdapter = new MiddleBirdAdapter($middleBird);

$human->eat($middleBirdAdapter); // Yummy

Thoughts

It feels like creating a method that wraps behavior defined in the interface. You need to carefully consider where to use it.

References

Tags: Adapter Pattern GoF PHP Design Patterns
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles