2.2. Bridge

2.2.1. Purpose

Decouple an abstraction from its implementation so that the two can varyindependently.

2.2.2. Examples

2.2.3. UML Diagram

Alt Bridge UML Diagram

2.2.4. Code

You can also find this code on GitHub

FormatterInterface.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Structural\Bridge;
  4.  
  5. interface FormatterInterface
  6. {
  7. public function format(string $text);
  8. }

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. class HtmlFormatter implements FormatterInterface
  6. {
  7. public function format(string $text)
  8. {
  9. return sprintf('<p>%s</p>', $text);
  10. }
  11. }

Service.php

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

HelloWorldService.php

  1. <?php
  2.  
  3. namespace DesignPatterns\Structural\Bridge;
  4.  
  5. class HelloWorldService extends Service
  6. {
  7. public function get()
  8. {
  9. return $this->implementation->format('Hello World');
  10. }
  11. }

2.2.5. Test

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. }
  21. }