BehavioralPHPverifiedVerified

Template Method Pattern in PHP

Defines the skeleton of an algorithm in a base class, deferring certain steps to subclasses without changing the algorithm's overall structure.

How to Implement the Template Method Pattern in PHP

1Step 1: Define the abstract class with the template method

abstract class DataProcessor
{
    // Template method — defines the algorithm skeleton
    final public function process(string $source): string
    {
        $raw = $this->readData($source);
        $parsed = $this->parseData($raw);
        $result = $this->transformData($parsed);
        return $this->formatOutput($result);
    }

    // Steps to be implemented by subclasses
    abstract protected function readData(string $source): string;
    abstract protected function parseData(string $raw): array;

    // Hook with default implementation
    protected function transformData(array $data): array
    {
        return $data; // No transformation by default
    }

    protected function formatOutput(array $data): string
    {
        return json_encode($data);
    }
}

2Step 2: Implement concrete subclasses

class CsvProcessor extends DataProcessor
{
    protected function readData(string $source): string
    {
        return "name,age\nAlice,30\nBob,25";
    }

    protected function parseData(string $raw): array
    {
        $lines = explode("\n", $raw);
        $headers = str_getcsv(array_shift($lines));
        return array_map(
            fn(string $line) => array_combine($headers, str_getcsv($line)),
            $lines,
        );
    }
}

class JsonProcessor extends DataProcessor
{
    protected function readData(string $source): string
    {
        return '[{"name":"Alice","age":30}]';
    }

    protected function parseData(string $raw): array
    {
        return json_decode($raw, true);
    }
}

// Usage
$csv = new CsvProcessor();
echo $csv->process('data.csv');

Template Method Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Template Method Pattern in the Real World

Consider a recipe for baking bread. The overall process—mix, knead, let rise, bake, cool—is fixed. But the specific flour blend, kneading technique, and baking temperature are decisions left to the baker. The cookbook provides the invariant sequence; individual bakers customize the steps that can vary without disrupting the overall process.