CreationalPHPverifiedVerified

Prototype Pattern in PHP

Creates new objects by cloning an existing instance, avoiding the cost of building from scratch.

How to Implement the Prototype Pattern in PHP

1Step 1: Define a cloneable prototype

class Shape
{
    public function __construct(
        public string $type,
        public float $x = 0,
        public float $y = 0,
        public string $color = 'black',
    ) {}

    // PHP has built-in clone support via __clone
    public function __clone(): void
    {
        // Deep copy logic for nested objects goes here
    }
}

2Step 2: Implement a prototype registry

class ShapeRegistry
{
    /** @var array<string, Shape> */
    private array $prototypes = [];

    public function register(string $key, Shape $prototype): void
    {
        $this->prototypes[$key] = $prototype;
    }

    public function create(string $key): Shape
    {
        if (!isset($this->prototypes[$key])) {
            throw new \RuntimeException("Prototype not found: {$key}");
        }
        return clone $this->prototypes[$key];
    }
}

3Step 3: Use the prototype pattern

$registry = new ShapeRegistry();
$registry->register('redCircle', new Shape('circle', color: 'red'));
$registry->register('blueSquare', new Shape('square', color: 'blue'));

$shape1 = $registry->create('redCircle');
$shape2 = $registry->create('redCircle');
$shape1->x = 10;

echo $shape1->x; // 10
echo $shape2->x; // 0 (independent clone)

Prototype Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Prototype Pattern in the Real World

Think of a cell dividing through mitosis. Instead of building a new cell from raw amino acids, the existing cell duplicates itself — copying its DNA, organelles, and membrane. The result is a fully functional copy produced far faster than assembling one molecule at a time.