DEV Community

Cover image for Learning Design Patterns with PHP - Bridge Pattern
Kenta Takeuchi
Kenta Takeuchi

Posted on • Originally published at bmf-tech.com

Learning Design Patterns with PHP - Bridge Pattern

This article was originally published on bmf-tech.com.

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
Enter fullscreen mode Exit fullscreen mode

Thoughts

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

References

Top comments (0)