CreationalPHPverifiedVerified

Abstract Factory Pattern in PHP

Provides an interface for creating families of related objects without specifying their concrete classes.

How to Implement the Abstract Factory Pattern in PHP

1Step 1: Define product interfaces for the UI component family

interface Button
{
    public function render(): string;
}

interface Checkbox
{
    public function render(): string;
}

2Step 2: Define the abstract factory interface

interface UIFactory
{
    public function createButton(): Button;
    public function createCheckbox(): Checkbox;
}

3Step 3: Implement concrete products for each theme

class DarkButton implements Button
{
    public function render(): string { return '<button class="dark">Click</button>'; }
}

class DarkCheckbox implements Checkbox
{
    public function render(): string { return '<input type="checkbox" class="dark"/>'; }
}

class LightButton implements Button
{
    public function render(): string { return '<button class="light">Click</button>'; }
}

class LightCheckbox implements Checkbox
{
    public function render(): string { return '<input type="checkbox" class="light"/>'; }
}

4Step 4: Implement concrete factories that produce consistent families

class DarkThemeFactory implements UIFactory
{
    public function createButton(): Button { return new DarkButton(); }
    public function createCheckbox(): Checkbox { return new DarkCheckbox(); }
}

class LightThemeFactory implements UIFactory
{
    public function createButton(): Button { return new LightButton(); }
    public function createCheckbox(): Checkbox { return new LightCheckbox(); }
}

5Step 5: Client code works with the factory abstraction

function renderUI(UIFactory $factory): void
{
    $button = $factory->createButton();
    $checkbox = $factory->createCheckbox();
    echo $button->render() . "\n" . $checkbox->render() . "\n";
}

renderUI(new DarkThemeFactory());

Abstract Factory Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Abstract Factory Pattern in the Real World

Imagine furnishing a room from IKEA versus a luxury boutique. Each store (factory) produces a complete set of furniture — chairs, tables, sofas — that share a consistent style. You pick the store, and every piece you get matches. You never mix a rustic IKEA chair with a baroque boutique table.