StructuralPHPverifiedVerified

Bridge Pattern in PHP

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

How to Implement the Bridge Pattern in PHP

1Step 1: Define the implementation interface (the "bridge")

interface Renderer
{
    public function renderCircle(float $x, float $y, float $radius): string;
    public function renderSquare(float $x, float $y, float $side): string;
}

2Step 2: Implement concrete implementations

class SvgRenderer implements Renderer
{
    public function renderCircle(float $x, float $y, float $radius): string
    {
        return "<circle cx=\"{$x}\" cy=\"{$y}\" r=\"{$radius}\"/>";
    }

    public function renderSquare(float $x, float $y, float $side): string
    {
        return "<rect x=\"{$x}\" y=\"{$y}\" width=\"{$side}\" height=\"{$side}\"/>";
    }
}

class CanvasRenderer implements Renderer
{
    public function renderCircle(float $x, float $y, float $radius): string
    {
        return "ctx.arc({$x}, {$y}, {$radius}, 0, 2*PI)";
    }

    public function renderSquare(float $x, float $y, float $side): string
    {
        return "ctx.fillRect({$x}, {$y}, {$side}, {$side})";
    }
}

3Step 3: Define the abstraction that uses the implementation

abstract class Shape
{
    public function __construct(protected Renderer $renderer) {}
    abstract public function draw(): string;
}

class CircleShape extends Shape
{
    public function __construct(
        Renderer $renderer,
        private readonly float $x,
        private readonly float $y,
        private readonly float $radius,
    ) {
        parent::__construct($renderer);
    }

    public function draw(): string
    {
        return $this->renderer->renderCircle($this->x, $this->y, $this->radius);
    }
}

// Usage — shape and renderer vary independently
$svg = new CircleShape(new SvgRenderer(), 10, 20, 5);
$canvas = new CircleShape(new CanvasRenderer(), 10, 20, 5);
echo $svg->draw();    // SVG output
echo $canvas->draw(); // Canvas output

Bridge Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Bridge Pattern in the Real World

A TV remote (abstraction) works with any brand of television (implementation) because both sides communicate through an agreed IR protocol (the bridge). Samsung and LG can redesign their TVs, and universal remote makers can add new button layouts—neither side needs to know about the other’s internal design, only the shared protocol.