DEV Community

Cover image for Learning Design Patterns with PHP - Adapter Pattern
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Learning Design Patterns with PHP - Adapter Pattern

This article was originally published on bmf-tech.com.

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
Enter fullscreen mode Exit fullscreen mode

Thoughts

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

References

Top comments (0)