To translate one interface for a class into a compatible interface. An
adapter allows classes to work together that normally could not because
of incompatible interfaces by providing its interface to clients while
using the original interface.

<?phpnamespaceDesignPatterns\Structural\Adapter;/** * This is the adapter here. Notice it implements BookInterface, * therefore you don't have to change the code of the client which is using a Book */classEBookAdapterimplementsBookInterface{/** * @var EBookInterface */protected$eBook;/** * @param EBookInterface $eBook */publicfunction__construct(EBookInterface$eBook){$this->eBook=$eBook;}/** * This class makes the proper translation from one interface to another. */publicfunctionopen(){$this->eBook->unlock();}publicfunctionturnPage(){$this->eBook->pressNext();}/** * notice the adapted behavior here: EBookInterface::getPage() will return two integers, but BookInterface * supports only a current page getter, so we adapt the behavior here * * @return int */publicfunctiongetPage():int{return$this->eBook->getPage()[0];}}

EBookInterface.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

<?phpnamespaceDesignPatterns\Structural\Adapter;interfaceEBookInterface{publicfunctionunlock();publicfunctionpressNext();/** * returns current page and total number of pages, like [10, 100] is page 10 of 100 * * @return int[] */publicfunctiongetPage():array;}

<?phpnamespaceDesignPatterns\Structural\Adapter;/** * this is the adapted class. In production code, this could be a class from another package, some vendor code. * Notice that it uses another naming scheme and the implementation does something similar but in another way */classKindleimplementsEBookInterface{/** * @var int */private$page=1;/** * @var int */private$totalPages=100;publicfunctionpressNext(){$this->page++;}publicfunctionunlock(){}/** * returns current page and total number of pages, like [10, 100] is page 10 of 100 * * @return int[] */publicfunctiongetPage():array{return[$this->page,$this->totalPages];}}