2.2. Bridge
You can also find this code on
PlainTextFormatter.php
- <?php
- namespace DesignPatterns\Structural\Bridge;
- class PlainTextFormatter implements FormatterInterface
- {
- public function format(string $text)
- {
- return $text;
- }
- }
HtmlFormatter.php
- <?php
- namespace DesignPatterns\Structural\Bridge;
- {
- /**
- * @var FormatterInterface
- */
- protected $implementation;
- /**
- * @param FormatterInterface $printer
- */
- public function __construct(FormatterInterface $printer)
- {
- $this->implementation = $printer;
- }
- /**
- * @param FormatterInterface $printer
- */
- public function setImplementation(FormatterInterface $printer)
- {
- $this->implementation = $printer;
- }
- abstract public function get();
- }
HelloWorldService.php
Tests/BridgeTest.php
- <?php
- namespace DesignPatterns\Structural\Bridge\Tests;
- use DesignPatterns\Structural\Bridge\HelloWorldService;
- use DesignPatterns\Structural\Bridge\HtmlFormatter;
- use DesignPatterns\Structural\Bridge\PlainTextFormatter;
- use PHPUnit\Framework\TestCase;
- class BridgeTest extends TestCase
- {
- public function testCanPrintUsingThePlainTextPrinter()
- {
- $service = new HelloWorldService(new PlainTextFormatter());
- $this->assertEquals('Hello World', $service->get());
- // now change the implementation and use the HtmlFormatter instead
- $service->setImplementation(new HtmlFormatter());
- $this->assertEquals('<p>Hello World</p>', $service->get());
- }