PHP Template Method Pattern
A short screencast: the Template Method pattern — defines the skeleton of an algorithm, letting subclasses redefine steps. Example of brewing tea and coffee.
Overview
The Template Method defines the overall sequence of steps in an algorithm while letting subclasses implement some of those steps. The abstract base class CaffeineBeverage contains the prepareRecipe() method marked as final — this is the template method. Common steps (boilWater, pourInCup) are implemented in the base class, while variable steps (brew, addCondiments) are declared abstract. Subclasses Tea and Coffee provide their own implementations for those steps.
UML diagram
Code
CaffeineBeverage.php
abstract class CaffeineBeverage
{
final public function prepareRecipe(): void
{
$this->boilWater();
$this->brew();
$this->pourInCup();
$this->addCondiments();
}
protected function boilWater(): void
{
echo "Boiling water\n";
}
protected function pourInCup(): void
{
echo "Pouring into cup\n";
}
abstract protected function brew(): void;
abstract protected function addCondiments(): void;
}
Tea.php
class Tea extends CaffeineBeverage
{
protected function brew(): void
{
echo "Steeping the tea\n";
}
protected function addCondiments(): void
{
echo "Adding lemon\n";
}
}
Coffee.php
class Coffee extends CaffeineBeverage
{
protected function brew(): void
{
echo "Dripping coffee through filter\n";
}
protected function addCondiments(): void
{
echo "Adding sugar and milk\n";
}
}
demo.php
require_once 'CaffeineBeverage.php';
require_once 'Tea.php';
require_once 'Coffee.php';
$tea = new Tea;
$tea->prepareRecipe();
echo "\n";
$coffee = new Coffee;
$coffee->prepareRecipe();
Example output
Boiling water
Steeping the tea
Pouring into cup
Adding lemon
Boiling water
Dripping coffee through filter
Pouring into cup
Adding sugar and milk
Advantages
- Avoids code duplication by keeping the common algorithm in one place.
- Subclasses override only what actually differs.
- Easy to extend without changing the algorithm structure.
- Controls the sequence of steps.
When to use
- When multiple classes share a common algorithm but differ in some steps.
- When you want to avoid duplication across subclasses.
- When the order of steps must be fixed.
- When some steps are required by all subclasses.
Usage in Laravel
In Laravel the Template Method is common in abstract classes and traits. For example, migrations use base classes that define the sequence of operations while developers override specifics. Service providers and some packages also use abstract base classes with template methods to standardize behavior.