2.2. Bridge

2.2.1. Purpose

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

2.2.2. UML Diagram

Alt Bridge UML Diagram

2.2.3. Code

You can also find this code on GitHub

Formatter.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge;
 6
 7interface Formatter
 8{
 9    public function format(string $text): string;
10}

PlainTextFormatter.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge;
 6
 7class PlainTextFormatter implements Formatter
 8{
 9    public function format(string $text): string
10    {
11        return $text;
12    }
13}

HtmlFormatter.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge;
 6
 7class HtmlFormatter implements Formatter
 8{
 9    public function format(string $text): string
10    {
11        return sprintf('<p>%s</p>', $text);
12    }
13}

Service.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge;
 6
 7abstract class Service
 8{
 9    public function __construct(protected Formatter $implementation)
10    {
11    }
12
13    final public function setImplementation(Formatter $printer)
14    {
15        $this->implementation = $printer;
16    }
17
18    abstract public function get(): string;
19}

HelloWorldService.php

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

PingService.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge;
 6
 7class PingService extends Service
 8{
 9    public function get(): string
10    {
11        return $this->implementation->format('pong');
12    }
13}

2.2.4. Test

Tests/BridgeTest.php

 1<?php
 2
 3declare(strict_types=1);
 4
 5namespace DesignPatterns\Structural\Bridge\Tests;
 6
 7use DesignPatterns\Structural\Bridge\HelloWorldService;
 8use DesignPatterns\Structural\Bridge\HtmlFormatter;
 9use DesignPatterns\Structural\Bridge\PlainTextFormatter;
10use PHPUnit\Framework\TestCase;
11
12class BridgeTest extends TestCase
13{
14    public function testCanPrintUsingThePlainTextFormatter()
15    {
16        $service = new HelloWorldService(new PlainTextFormatter());
17
18        $this->assertSame('Hello World', $service->get());
19    }
20
21    public function testCanPrintUsingTheHtmlFormatter()
22    {
23        $service = new HelloWorldService(new HtmlFormatter());
24
25        $this->assertSame('<p>Hello World</p>', $service->get());
26    }
27}