StructuralPHPverifiedVerified

Composite Pattern in PHP

Composes objects into tree structures to represent part-whole hierarchies, letting clients treat individual objects and compositions uniformly.

How to Implement the Composite Pattern in PHP

1Step 1: Define the component interface

interface FileSystemEntry
{
    public function getName(): string;
    public function getSize(): int;
    public function display(string $indent = ''): string;
}

2Step 2: Implement the leaf node

class File implements FileSystemEntry
{
    public function __construct(
        private readonly string $name,
        private readonly int $size,
    ) {}

    public function getName(): string { return $this->name; }
    public function getSize(): int { return $this->size; }
    public function display(string $indent = ''): string
    {
        return "{$indent}- {$this->name} ({$this->size}B)\n";
    }
}

3Step 3: Implement the composite node

class Directory implements FileSystemEntry
{
    /** @var FileSystemEntry[] */
    private array $children = [];

    public function __construct(private readonly string $name) {}

    public function add(FileSystemEntry $entry): self
    {
        $this->children[] = $entry;
        return $this;
    }

    public function getName(): string { return $this->name; }

    public function getSize(): int
    {
        return array_sum(array_map(fn(FileSystemEntry $e) => $e->getSize(), $this->children));
    }

    public function display(string $indent = ''): string
    {
        $output = "{$indent}+ {$this->name}/\n";
        foreach ($this->children as $child) {
            $output .= $child->display($indent . '  ');
        }
        return $output;
    }
}

// Usage
$root = new Directory('root');
$root->add(new File('readme.md', 1024))
     ->add((new Directory('src'))
         ->add(new File('app.php', 2048))
         ->add(new File('index.php', 512)));

echo $root->display();
echo "Total size: {$root->getSize()}B\n";

Composite Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Composite Pattern in the Real World

A company’s org chart is a composite structure. An individual employee (leaf) has a salary and a name. A department (composite) also has a name and a budget—calculated by summing the salaries of all its members, which may themselves be other departments. HR can call ‘get budget’ on the CEO’s node and the entire tree is summed recursively.