PHP Design Patterns .

PHP Design Patterns Adapter

About the Adapter


In the Adapter Design Pattern, a class converts the interface of one class to be what another class expects.

In this example we have a SimpleBook class that has a getAuthor() and getTitle() methods. The client, testAdapter.php, expects a getAuthorAndTitle() method. To "adapt" SimpleBook for testAdapter we have an adapter class, BookAdapter, which takes in an instance of SimpleBook, and uses the SimpleBook getAuthor() and getTitle() methods in it's own getAuthorAndTitle() method.

Adapters are helpful if you want to use a class that doesn't have quite the exact methods you need, and you can't change the orignal class. The adapter can take the methods you can access in the original class, and adapt them into the methods you need.


SimpleBook.php

//copyright Lawrence Truett and FluffyCat.com 2006, all rights reserved
  
  class SimpleBook {

private $author; private $title;

function __construct($author_in, $title_in) { $this->author = $author_in; $this->title = $title_in; }

function getAuthor() {return $this->author;}

function getTitle() {return $this->title;}

}
To download source right-click here and "Save As...".

BookAdapter.php

//copyright Lawrence Truett and FluffyCat.com 2006, all rights reserved
  
  include_once('SimpleBook.php');
  
  class BookAdapter {

private $book;

function __construct(SimpleBook $book_in) { $this->book = $book_in; }

function getAuthorAndTitle() { return $this->book->getTitle() . ' by ' . $this->book->getAuthor(); }

}
To download source right-click here and "Save As...".


testAdapter.php

//copyright Lawrence Truett and FluffyCat.com 2006, all rights reserved

include_once('SimpleBook.php'); include_once('BookAdapter.php');

define('BR', '<'.'BR'.'>');

echo 'BEGIN TESTING ADAPTER PATTERN'.BR; echo BR;

$book = new SimpleBook("Gamma, Helm, Johnson, and Vlissides", "Design Patterns"); $bookAdapter = new BookAdapter($book); echo 'Author and Title: '.$bookAdapter->getAuthorAndTitle();

echo BR.BR; echo 'END TESTING ADAPTER PATTERN'.BR;
To download source right-click here and "Save As...".

output of testAdapter.php

BEGIN TESTING ADAPTER PATTERN

Author and Title: Design Patterns by Gamma, Helm, Johnson, and Vlissides

END TESTING ADAPTER PATTERN

References


Design Patterns
Design Patterns by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides

PHP 5
The Official PHP web site
Core PHP Programming, 3rd Edition by Leon Atkinson and Zeev Suraski
Comments Comments are left by visitors to FluffyCat.com and may or may not be accurate.
Comment by Larry on 2012-08-27 Rate this Comment

The Adapter Pattern and the Decorator Pattern are similar in that they both fill the need to convert a class to a different interface without changing orignal the class. The essential difference is that the Decorator Pattern adds some functionality, while the Adapter Pattern does not.

 
Sign in to comment on PHP Design Patterns Adapter.