Our PHP Design Patterns Game adventure continues with three different worlds: a forest, a frozen kingdom, and a volcanic fortress. Each environment contains its own enemies and rewards, but the player should not need a different game engine for every world.
We could fill the engine with conditional statements that inspect the selected world and create the appropriate objects. That approach works for a small prototype, but the branching logic grows whenever a new environment or object type is introduced.
The Abstract Factory pattern offers another approach. It defines an interface for creating families of related objects without requiring the client to know their concrete classes.
The Game Design Problem
Imagine that each world must provide an enemy and a reward. Forest encounters should create forest creatures and woodland treasures. Ice encounters should create frozen guardians and ice crystals. Volcanic encounters should create fire creatures and volcanic artifacts.
The important requirement is consistency. A forest factory should not accidentally create an ice guardian paired with a volcanic reward.
Abstract Factory groups related creation operations behind a common contract. The engine asks the selected factory for an enemy and a reward, then plays the encounter through shared interfaces.
Step 1: Define the Game Products
Our first interfaces represent the two kinds of objects the engine needs.
<?php
declare(strict_types=1);
interface Enemy
{
public function name(): string;
public function damage(): int;
}
interface Reward
{
public function name(): string;
public function gold(): int;
}The game does not need to know whether an enemy is made of ice, fire, or something else. It only needs its name and attack damage. Likewise, every reward exposes a name and gold value.
Step 2: Implement the World Objects
To keep the example compact, we will use two reusable concrete product classes. Their values are supplied by the factories, which represent the different worlds.
final readonly class Creature implements Enemy
{
public function __construct(
private string $label,
private int $attack
) {
}
public function name(): string
{
return $this->label;
}
public function damage(): int
{
return $this->attack;
}
}
final readonly class Treasure implements Reward
{
public function __construct(
private string $label,
private int $value
) {
}
public function name(): string
{
return $this->label;
}
public function gold(): int
{
return $this->value;
}
}This design keeps the products simple while allowing each factory to define a coherent combination. In a larger game, individual worlds might provide different concrete enemy and reward classes with more specialized behavior.
Step 3: Create the Abstract Factory Contract
The central interface describes the family of objects that every world must provide.
interface WorldFactory
{
public function worldName(): string;
public function createEnemy(): Enemy;
public function createReward(): Reward;
}Notice that the factory returns interfaces rather than concrete product types. The engine can therefore work with any implementation of WorldFactory.
Step 4: Build Three World Factories
Each factory provides its own family of related objects.
final class ForestFactory implements WorldFactory
{
public function worldName(): string
{
return 'Enchanted Forest';
}
public function createEnemy(): Enemy
{
return new Creature('Forest Wolf', 12);
}
public function createReward(): Reward
{
return new Treasure('Emerald Leaf', 40);
}
}
final class IceFactory implements WorldFactory
{
public function worldName(): string
{
return 'Frozen Kingdom';
}
public function createEnemy(): Enemy
{
return new Creature('Ice Guardian', 18);
}
public function createReward(): Reward
{
return new Treasure('Frost Crystal', 70);
}
}
final class VolcanoFactory implements WorldFactory
{
public function worldName(): string
{
return 'Volcanic Fortress';
}
public function createEnemy(): Enemy
{
return new Creature('Lava Beast', 25);
}
public function createReward(): Reward
{
return new Treasure('Fire Ruby', 100);
}
}The three factories have the same public interface but produce different configurations. Adding a new world does not require modifying the existing factories.
Step 5: Play Without Knowing the World
Now the game engine can receive any WorldFactory implementation and play an encounter without checking which world was selected.
function playWorld(
WorldFactory $factory,
int $health
): array {
$enemy = $factory->createEnemy();
$reward = $factory->createReward();
$remaining = max(
0,
$health - $enemy->damage()
);
echo 'World: ', $factory->worldName(), PHP_EOL;
echo 'Enemy: ', $enemy->name(), PHP_EOL;
echo 'Health: ', $remaining, PHP_EOL;
$earnedGold = 0;
if ($remaining > 0) {
$earnedGold = $reward->gold();
echo 'Reward: ', $reward->name(),
' (+', $earnedGold, ' gold)', PHP_EOL;
} else {
echo 'The player was defeated.', PHP_EOL;
}
echo PHP_EOL;
return [$remaining, $earnedGold];
}
$health = 100;
$totalGold = 0;
$worlds = [
new ForestFactory(),
new IceFactory(),
new VolcanoFactory(),
];
foreach ($worlds as $world) {
[$health, $gold] = playWorld($world, $health);
$totalGold += $gold;
if ($health === 0) {
break;
}
}
echo "Final health: {$health}\n";
echo "Total gold: {$totalGold}\n";The game visits the forest, ice kingdom, and volcanic fortress in sequence. With the example values, the player finishes with 45 health points and collects 210 gold.
The expected final output is:
Final health: 45
Total gold: 210The result is deterministic because the example does not use randomness or interactive combat. A production game would introduce additional mechanics, but the factory structure would remain applicable.
Abstract Factory Versus Factory Method
These two patterns are frequently confused because both involve object creation.
Abstract Factory provides an interface for creating a family of related products. In this example, each world factory creates both an enemy and a reward.
Factory Method focuses on a creation method whose implementation can vary, often through subclassing. It does not necessarily organize several related product types into one family.
The distinction becomes clearer when a game introduces multiple related objects that must belong to the same environment. That is where Abstract Factory becomes particularly useful.
When Is This Pattern Worth the Complexity?
Abstract Factory is useful when an application supports several interchangeable families of related objects and the client should remain independent of their concrete implementations.
Outside games, examples include user-interface component families, database-driver abstractions, document-rendering systems, and platform-specific services.
However, the pattern introduces interfaces and additional classes. If an application creates only one simple object and has no requirement to support alternative families, a direct constructor or a small factory function may be easier to maintain.
There is another tradeoff: adding a new world is straightforward, but adding a new product category, such as createWeapon(), requires changing the factory interface and every implementation.
That is the characteristic balance of Abstract Factory: it makes product families interchangeable while making the set of product types relatively stable.
Reader Challenge: The Fourth World
Create a DesertFactory with a Sand Scorpion enemy and an Ancient Coin reward. The new world should work with playWorld() without changing the engine.
For an advanced challenge, add a second enemy type to each world and decide whether the existing factory interface still represents the game’s needs effectively.
The objective is to preserve consistency between related objects while keeping the engine independent of world-specific creation details.

















![PHP #[Override]: Catching Broken Inheritance Contracts Before Production](https://phpmagazine.net/wp-content/uploads/2026/11/php-override-218x150.png)






