What It Is
The Template Method pattern fixes the skeleton of an algorithm — the steps and their order — while letting the individual steps vary. The recipe is written once; each variant fills in its own steps.
PHP does it the classic way: an abstract base class owns a final skeleton method, and abstract protected methods are the steps every subclass must provide.
Example: One Recipe, Two Drinks
make() owns the order: boil, brew, pour, extras. Tea and coffee only answer how to brew and what to add — final means they cannot reorder or skip steps.
The skeleton stays fixed
Both drinks follow the same four steps in the same order, because the order lives in one final method. A new drink implements two methods and inherits the whole discipline.
Output: PHP script
<?php
abstract class Drink {
public function __construct(protected string $name) {}
// The fixed skeleton — final, so no drink can reorder the steps.
final public function make(): void {
echo "-- ", $this->name, "\n";
echo "boil water\n";
echo $this->brew(), "\n";
echo "pour into cup\n";
echo $this->extras(), "\n";
}
// The variable steps every drink must fill in.
abstract protected function brew(): string;
abstract protected function extras(): string;
}
class Tea extends Drink {
protected function brew(): string { return "steep the tea leaves"; }
protected function extras(): string { return "add lemon"; }
}
class Coffee extends Drink {
protected function brew(): string { return "run water through the coffee"; }
protected function extras(): string { return "add milk"; }
}
(new Tea("tea"))->make();
(new Coffee("coffee"))->make();
When to Use It
Use it when several procedures share the same fixed sequence with different details — report generation, import pipelines, test setups.
Skip it when the variants also need different orders — forcing them under one skeleton bends the pattern until it breaks. And with one variant, the skeleton is just a function.
Pros and Cons
Pros: the sequence is enforced in one place; variants cannot forget or shuffle steps; shared steps are written once.
Cons: rigid by design — a variant that needs "almost the same, but..." fights the skeleton; too many hook methods make the recipe hard to follow.