StructuralPHPverifiedVerified

Flyweight Pattern in PHP

Minimizes memory usage by sharing fine-grained objects that represent repeated data, storing intrinsic state once and passing extrinsic state at call time.

How to Implement the Flyweight Pattern in PHP

1Step 1: Define the flyweight that holds shared (intrinsic) state

class TreeType
{
    public function __construct(
        public readonly string $name,
        public readonly string $color,
        public readonly string $texture,
    ) {}

    public function draw(float $x, float $y): string
    {
        return "Drawing {$this->name} at ({$x},{$y}) color={$this->color}";
    }
}

2Step 2: Implement the flyweight factory

class TreeFactory
{
    /** @var array<string, TreeType> */
    private static array $types = [];

    public static function getTreeType(string $name, string $color, string $texture): TreeType
    {
        $key = "{$name}_{$color}_{$texture}";

        if (!isset(self::$types[$key])) {
            self::$types[$key] = new TreeType($name, $color, $texture);
            echo "Created new TreeType: {$key}\n";
        }

        return self::$types[$key];
    }

    public static function getTypeCount(): int
    {
        return count(self::$types);
    }
}

3Step 3: Context holds unique (extrinsic) state

class Tree
{
    public function __construct(
        private readonly float $x,
        private readonly float $y,
        private readonly TreeType $type,
    ) {}

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

// Usage — many trees share few TreeType instances
$forest = [];
for ($i = 0; $i < 1000; $i++) {
    $type = TreeFactory::getTreeType('Oak', 'green', 'rough');
    $forest[] = new Tree(rand(0, 500), rand(0, 500), $type);
}
echo "Trees: " . count($forest) . ", Types: " . TreeFactory::getTypeCount(); // 1000 trees, 1 type

Flyweight Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Flyweight Pattern in the Real World

A book publisher doesn’t print a separate metal typeface block for every letter ‘e’ on every page. Instead, one block for ‘e’ (intrinsic state) is reused in every position, with the printer supplying the ink color and position (extrinsic state) each time it is stamped. Thousands of impressions share one piece of metal.