Welcome to another installment of PHP Design Patterns Game. Today, our dungeon contains individual enemies, enemy squads, and larger groups that contain other groups.

The challenge is deceptively simple: how can the game calculate damage from a single enemy and from an entire army without maintaining two completely different combat systems?

The Composite pattern provides an answer by allowing individual objects and collections of objects to implement the same interface.

The Problem: One Enemy or an Entire Squad?

Suppose our game has skeletons, bats, and dungeon guardians. Each enemy has an attack value.

At first, calculating the damage inflicted by one enemy is easy. But what happens when enemies form squads, and squads become part of larger encounters?

We could write separate functions for enemies, squads, and armies. That approach quickly introduces repeated branching logic and special cases.

Composite offers a different structure: every combat unit exposes the same operations, whether it represents one creature or many.

Step 1: Define a Common Combat Interface

We begin with an interface describing the operations that every combat unit must support.

<?php

declare(strict_types=1);

interface CombatUnit
{
    public function name(): string;

    public function damage(): int;
}

The interface says nothing about how damage is calculated. That decision belongs to each implementation.

Step 2: Create Individual Enemies

An individual enemy is a leaf in the Composite structure. It does not contain other combat units.

final readonly class Enemy implements CombatUnit
{
    public function __construct(
        private string $enemyName,
        private int $attack
    ) {
        if ($attack < 0) {
            throw new InvalidArgumentException(
                'Attack cannot be negative.'
            );
        }
    }

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

    public function damage(): int
    {
        return $this->attack;
    }
}

This implementation is deliberately small. An enemy has a name and a nonnegative attack value.

The readonly class declaration is supported in PHP 8.2 and prevents reassignment of initialized instance properties.

Step 3: Build the Composite

A squad implements the same interface but delegates damage calculation to its children.

final class EnemyGroup implements CombatUnit
{
    /** @var list<CombatUnit> */
    private array $members = [];

    public function __construct(
        private string $groupName
    ) {
    }

    public function add(CombatUnit $unit): void
    {
        if ($unit === $this) {
            throw new LogicException(
                'A group cannot contain itself.'
            );
        }

        $this->members[] = $unit;
    }

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

    public function damage(): int
    {
        $total = 0;

        foreach ($this->members as $member) {
            $total += $member->damage();
        }

        return $total;
    }
}

The important line is the call to $member->damage(). The group does not need to know whether a member is an individual enemy or another group.

Both implement CombatUnit, so the same operation works at every level.

The direct self-reference check prevents the simplest invalid relationship. It does not prevent longer cycles involving several groups; a production implementation would need stronger cycle detection or a tree structure that makes cycles impossible.

Step 4: Assemble the Dungeon Encounter

We can now combine individual enemies into groups and combine those groups into a larger encounter.

$skeletons = new EnemyGroup('Skeleton Squad');

$skeletons->add(new Enemy('Skeleton A', 8));
$skeletons->add(new Enemy('Skeleton B', 8));

$bats = new EnemyGroup('Bat Swarm');

$bats->add(new Enemy('Bat A', 3));
$bats->add(new Enemy('Bat B', 3));
$bats->add(new Enemy('Bat C', 3));

$dungeon = new EnemyGroup('Dungeon Encounter');

$dungeon->add($skeletons);
$dungeon->add($bats);
$dungeon->add(new Enemy('Guardian', 15));

echo $skeletons->name(), ': ',
    $skeletons->damage(), PHP_EOL;

echo $bats->name(), ': ',
    $bats->damage(), PHP_EOL;

echo $dungeon->name(), ': ',
    $dungeon->damage(), PHP_EOL;

Expected output:

Skeleton Squad: 16
Bat Swarm: 9
Dungeon Encounter: 40

The complete encounter inflicts 40 points of damage: 16 from the skeleton squad, 9 from the bat swarm, and 15 from the guardian.

Step 5: Play the Encounter

Our player starts with 100 health points. The combat function accepts any CombatUnit, including an individual enemy or an entire nested encounter.

function fight(
    CombatUnit $opponent,
    int $health
): int {
    $remaining = max(
        0,
        $health - $opponent->damage()
    );

    echo 'Facing: ', $opponent->name(), PHP_EOL;
    echo 'Health remaining: ', $remaining, PHP_EOL;

    return $remaining;
}

$health = 100;

$health = fight($dungeon, $health);

assert($health === 60);

The player finishes with 60 health points. The fight() function does not contain special handling for groups, squads, or individual enemies.

For a deterministic check independent of PHP assertion configuration, replace the final assertion with an explicit comparison and exception.

Why Composite Works Here

The Composite pattern establishes a tree-like structure with two principal roles.

Leaves represent individual objects. Composites contain other objects that implement the same component interface.

The client communicates through that interface rather than inspecting the concrete type of every object.

In our game, Enemy is a leaf, EnemyGroup is a composite, and CombatUnit is the common interface.

The result is a recursive structure in which the same damage() operation applies to one enemy, one squad, or an entire dungeon encounter.

Where the Pattern Becomes Dangerous

Composite is not free of tradeoffs. Recursive structures can be difficult to debug when they become deeply nested.

Mutable groups can also introduce shared-reference problems. If the same EnemyGroup is added to multiple parents, changes to that group affect every parent that references it.

Cycles are especially dangerous. A group that indirectly contains itself can cause unbounded recursive calls when calculating damage.

Production implementations should define ownership rules, validate additions, and decide whether the structure must remain a strict tree.

For a fixed list of enemies with no nesting, a simple array and loop may be easier to maintain. Composite becomes valuable when hierarchical composition is an actual domain requirement.

Beyond Games: Real Applications

The same structure appears in graphical interfaces, document trees, filesystem abstractions, organizational hierarchies, and nested business rules.

A user-interface container may hold individual controls and other containers. A document section may contain paragraphs and nested sections. A business rule group may contain individual rules and additional rule groups.

In each case, the central question is whether clients benefit from treating individual elements and collections through one common contract.

Reader Challenge: The Dungeon Commander

Extend EnemyGroup with a method that counts the total number of individual enemies, including those inside nested groups.

Then introduce a DungeonCommander enemy that adds a fixed bonus to the damage of the group it leads.

Finally, prevent indirect cycles when adding groups. Test the case where Group A contains Group B and an attempt is made to add Group A to Group B.

The challenge is to preserve the simplicity of the CombatUnit interface while making the hierarchy safe and predictable.

LEAVE A REPLY

Please enter your comment!
Please enter your name here