Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Home/PHP/Design patterns/Template Method
PHP

PHP

Pragmatic server-side language that powers a large share of the web.

Paradigm
OOP, procedural, functional features
Typing
Dynamic with gradual typing (strict_types)
Memory
Reference counting + cycle collector
Runs
Zend Engine, bytecode + OPcache, optional JIT
Concurrency
Shared-nothing per request; Fibers (8.1)
Behavioral pattern

Template Method

Intent

Defines the skeleton of an algorithm in a base class and lets subclasses override specific steps.

Problem

CSV, PDF and DOC importers share 80% of their steps, duplicated three times.

Solution

Put the shared steps in a base method that calls abstract or hook steps overridden by subclasses.

Real-world analogy

Think of it like this

Houses built from a standard plan: the builder follows the same steps, and each owner customises a few (windows, finishes).

Structure

association / extends implements / depends on
AbstractClass + templateMethod()+ step1()+ step2() {abstract}+ step3() {hook} 1 ConcreteClass1 + step2() 2 ConcreteClass2 + step2()+ step3()

Hover or tap a numbered role to highlight it in the diagram.

  1. 1AbstractClass — Abstract Class defines templateMethod(), which calls the steps in order. Steps are abstract or have defaults.
  2. 2ConcreteClass1 — Concrete Classes override steps, never the template method itself.

Code example

A PHP code sample for Template Method is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Template Method when clients should extend only particular steps of an algorithm.

Use Template Method when several classes share almost identical algorithms.

Pros and cons

Pros

  • Reuse of shared code
  • Clients override only small parts

Cons

  • Limited by the skeleton
  • Can violate Liskov if subclasses suppress steps

Relations with other patterns

Check yourself

Check yourself

CSV, JSON and XML exporters all do open → write header → write rows → close; only formatting differs.

Saved in this browser only. Part of Behavioral patterns (0/11).