2.1. Adapter / Wrapper

    • DB Client libraries adapter
    • using multiple different webservices and adapters normalize data sothat the outcome is the same for all

    You can also find this code on GitHub

    Book.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Adapter;
    4.  
    5. class Book implements BookInterface
    6. {
    7. /**
    8. * @var int
    9. */
    10. private $page;
    11.  
    12. public function open()
    13. {
    14. $this->page = 1;
    15. }
    16.  
    17. public function turnPage()
    18. {
    19. $this->page++;
    20.  
    21. public function getPage(): int
    22. {
    23. return $this->page;
    24. }
    25. }

    EBookAdapter.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Adapter;
    4.  
    5. interface EBookInterface
    6. {
    7. public function unlock();
    8.  
    9. public function pressNext();
    10.  
    11. /**
    12. * returns current page and total number of pages, like [10, 100] is page 10 of 100
    13. *
    14. * @return int[]
    15. */
    16. public function getPage(): array;
    17. }

    Kindle.php

    Tests/AdapterTest.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Adapter\Tests;
    4. use DesignPatterns\Structural\Adapter\Book;
    5. use DesignPatterns\Structural\Adapter\EBookAdapter;
    6. use DesignPatterns\Structural\Adapter\Kindle;
    7. use PHPUnit\Framework\TestCase;
    8.  
    9. class AdapterTest extends TestCase
    10. {
    11. public function testCanTurnPageOnBook()
    12. {
    13. $book = new Book();
    14. $book->open();
    15. $book->turnPage();
    16.  
    17. $this->assertEquals(2, $book->getPage());
    18. }
    19.  
    20. public function testCanTurnPageOnKindleLikeInANormalBook()
    21. {
    22. $kindle = new Kindle();
    23. $book = new EBookAdapter($kindle);
    24.  
    25. $book->open();
    26. $book->turnPage();
    27.  
    28. $this->assertEquals(2, $book->getPage());
    29. }