Application 2019-02-01

Learning Design Patterns with PHP - Bridge Pattern

Understand the Bridge pattern to separate functional and implementation extensions using composition in PHP application design.

Read in: ja
Learning Design Patterns with PHP - Bridge Pattern

Overview

An article that didn't make it in time for the PHP Design Patterns Advent Calendar 2018.

What is the Bridge Pattern?

A pattern that prepares a superclass for functional extensions and a subclass for implementation extensions, acting as a bridge for functionality.

Implementation

<?php
interface Connector
{
    public function __construct(Converter $converter);
    public function connect();
}

class IphoneConnector implements Connector
{
    private $converter;

    public function __construct(Converter $converter)
    {
        $this->converter = $converter;
    }

    public function connect()
    {
        echo 'Iphone connect by using ' . $this->converter->getTerminalName();
    }
}

class AndroidConnector implements Connector
{
    private $converter;

    public function __construct(Converter $converter)
    {
        $this->converter = $converter;
    }

    public function connect()
    {
        echo 'Android connect by using ' . $this->converter->getTerminalName();
    }
}

interface Converter
{
    public function getTerminalName();
}

class LightningConverter implements Converter
{
    public function getTerminalName()
    {
        return 'lightning';
    }
}

class TypeCConverter implements Converter
{
    public function getTerminalName()
    {
        return 'type-c';
    }
}

$lightingConveter = new LightningConverter();
$typeCConverter = new TypeCConverter();

// Either converter can be used → Implementation can be switched
$iphoneConnector = new IphoneConnector($lightingConveter);
$androidConnector = new AndroidConnector($typeCConverter);

$iphoneConnector->connect(); // connect by using lighting
$androidConnector->connect(); // connect by using type-c

Thoughts

I feel like this is just a simple use of interfaces, which might indicate my understanding is still shallow.

References

Tags: GoF PHP Design Pattern Bridge Pattern
Share: 𝕏 Post Facebook Hatena
✏️ View source / Discuss on GitHub
☕ Support

If you enjoy this blog, consider supporting it. Every bit helps keep it running!


Related Articles