Design Pattern: Adapter in PHP

The next part in the Head First Design Pattern series covers the “Adapter Pattern”. Say for example you worked on an API. The API is out in the wild and is being used widely. Then the changes for the API come rolling in and you have to redesign the implementation. But, since you already have users using the API, you need to resort to a less disruptive solution. What do you do? Rewrite the old functions? An easier way would be to create an interface that would convert the old public interface of your API to the new interface.

Here’s a link to the zipped code if you want to tinker with it.

interface Duck{
    public function quack();
    public function fly();
}
interface Turkey{
    public function gobble();
    public function fly();
}
include_once("duck.php");
class MallardDuck implements Duck{
    public function quack(){
        echo("Quack");
    }

    public function fly(){
        echo("I'm flying");
    }
}
include_once("turkey.php");
class WildTurkey implements Turkey{
    public function gobble(){
        echo("Gobble gobble");
    }

    public function fly(){
        echo("I'm flying a short distance");
    }
}
include_once("duck.php");
class TurkeyAdapter implements Duck{

    private $turkey;

    public function __construct(Turkey $turkey){
        $this->turkey = $turkey;
    }

    public function quack(){
        $this->turkey->gobble();
    }

    public function fly(){
        $this->turkey->fly();
    }
}
include_once("mallardDuck.php");
include_once("wildTurkey.php");
include_once("turkeyAdapter.php");

class DuckTestDrive{
    public static function main(){
        $duck = new MallardDuck();
        $turkey = new WildTurkey();
        $turkeyAdapter = new TurkeyAdapter($turkey);

        echo("The turkey says ...");
        $turkey->gobble();
        echo("<br />");
        $turkey->fly();
        echo("<br />");

        echo("The duck says ...");
        self::testDuck($duck);
        echo("<br />");

        echo("The turkey adapter says ...");
        self::testDuck($turkeyAdapter);
        echo("<br />");

    }

    private static function testDuck(Duck $duck){
        $duck->quack();
        echo("<br />");
        $duck->fly();
    }
}

DuckTestDrive::main();

Leave a Reply




You may use the tags listed below in your comments:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>