2.2. Bridge

    You can also find this code on

    PlainTextFormatter.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Bridge;
    4.  
    5. class PlainTextFormatter implements FormatterInterface
    6. {
    7. public function format(string $text)
    8. {
    9. return $text;
    10. }
    11. }

    HtmlFormatter.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Bridge;
    4.  
    5. {
    6. /**
    7. * @var FormatterInterface
    8. */
    9. protected $implementation;
    10.  
    11. /**
    12. * @param FormatterInterface $printer
    13. */
    14. public function __construct(FormatterInterface $printer)
    15. {
    16. $this->implementation = $printer;
    17. }
    18.  
    19. /**
    20. * @param FormatterInterface $printer
    21. */
    22. public function setImplementation(FormatterInterface $printer)
    23. {
    24. $this->implementation = $printer;
    25. }
    26. abstract public function get();
    27. }

    HelloWorldService.php

    Tests/BridgeTest.php

    1. <?php
    2.  
    3. namespace DesignPatterns\Structural\Bridge\Tests;
    4.  
    5. use DesignPatterns\Structural\Bridge\HelloWorldService;
    6. use DesignPatterns\Structural\Bridge\HtmlFormatter;
    7. use DesignPatterns\Structural\Bridge\PlainTextFormatter;
    8. use PHPUnit\Framework\TestCase;
    9.  
    10. class BridgeTest extends TestCase
    11. {
    12. public function testCanPrintUsingThePlainTextPrinter()
    13. {
    14. $service = new HelloWorldService(new PlainTextFormatter());
    15. $this->assertEquals('Hello World', $service->get());
    16.  
    17. // now change the implementation and use the HtmlFormatter instead
    18. $service->setImplementation(new HtmlFormatter());
    19. $this->assertEquals('<p>Hello World</p>', $service->get());
    20. }