PHP Template Method Pattern Explained (its easy!)

PHP Template Method Pattern Explained (its easy!) Thumbnail image

This is part of my series on some common PHP design patterns. Today I'm looking at the Template Method Pattern.

I honestly had no idea that this design pattern was even called this until a while ago. It is a common way of doing things, and if you code in an object orientated programming language then you almost certainly just do this naturally.

Although this page title is about the Template Method Pattern in PHP, and all code samples will be in PHP this isn't anything specific to PHP. This can apply to many other programming languages too.

What is The Template Method Pattern?

It is a commonly used design pattern (especially in PHP, I think) that makes use of abstract classes.

I think the best way to explain programming concepts is with some easy to understand code.

An example - 'before' converting some code to use the template method

Let's pretend you are a vehicle manufacturer, creating both cars and vehicles.

You have 4 basic steps in creating a vehicle:

  • addEngine() (cars and motorbikes have different engines),
  • addWheels() (again, cars and motorbikes have different wheels),
  • paintVehicle() (but the basic process of painting is the same for cars and motorbikes (so the code is identical))
  • sellVehicle() (and again, the basic process of selling a car or motorbike is the same, so the code is identical

This is a very oversimplified example to get the point across. The code below also will be simplified to make explaining this easier)

It should be quite obvious how to handle this very simple example. A lot of the code can be shared. But let's begin with a bad implementation, spread over three files:

CarMaker.php

This is the class that contains all of the code for each step of making a car

  1. class CarMaker
  2. {
  3.     public function addWheels()
  4.     {
  5.         echo __METHOD__ . " 4 car Wheels were added\n";
  6.     }
  7.     public function addEngine()
  8.     {
  9.         echo __METHOD__ . " Car Engine was added\n";
  10.     }
  11.     public function paintVehicle()
  12.     {
  13.         echo __METHOD__ . " Painting vehicle";
  14.     }
  15.     public function sellVehicle()
  16.     {
  17.         echo __METHOD__ . " selling Vehicle";
  18.     }
  19. }
MotorbikeMaker.php

This is very similar to the above class. A lot of code was copy/pasted. However please note the addWheels() and addEngine() are different.

  1. class MotorbikeMaker
  2. {
  3.     public function addWheels()
  4.     {
  5.       // different than the CarMaker::addWheels() method
  6.         echo __METHOD__ . " 2 motorbike Wheels were added\n";
  7.     }
  8.     public function addEngine()
  9.     {
  10.        // this is different than the addEngine() above, as motorbike and car engines are different
  11.         echo __METHOD__ . " 1 Motorbike Engine was added\n";
  12.     }
  13.     public function paintVehicle()
  14.     {
  15.        // same as previous class' implementation of paintVehicle()
  16.         echo __METHOD__ . " Painting vehicle";
  17.     }
  18.     public function sellVehicle()
  19.     { // this is the same as the previous class' implementation of sellVehicle()
  20.         echo __METHOD__ . " selling Vehicle";
  21.     }
  22. }
MakeVehicles.php

This is the file that calls the above methods.

  1. $carmaker =  new CarMaker;
  2. $carmaker->addEngine();
  3. $carmaker->addWheels();
  4. $carmaker->paintVehicle();
  5. $carmaker->sellVehicle();
  6. echo "\n-----------------------------\n\n";
  7.  
  8. $motorbikemaker = new MotorbikeMaker;
  9. $motorbikemaker->addEngine();
  10. $motorbikemaker->addWheels();
  11. $motorbikemaker->paintVehicle();
  12. $motorbikemaker->sellVehicle();

Hopefully you can see some obvious ways how this can be improved.


Now time for the 'after' - with the template method. First, let's create a main abstract class

We can create one main abstract class, which calls the 4 template steps in one method, and has the code for any shared methods.

i.e. to put another way: for paintVehicle() and sellVehicle(), we will have a fully implemented method. For addEngine() and addWheels() (which have different implementations for each vehicle type) we will just have an abstract method, which will have to be implemented in a subclass)

VehicleMaker.php
  1. abstract class VehicleMaker
  2. {
  3.     // these two MUST be implemented by a sub class
  4.     // as the wheel or engines are specific to the type of vehicle
  5.     abstract protected function addWheels();
  6.     abstract protected function addEngine();
  7.  
  8.  
  9.     // however the process of painting (or selling) doesn't change, so we can have the same methods for all vehicle types
  10.     protected function paintVehicle()
  11.     {
  12.         echo __METHOD__ . " Painting vehicle\n";
  13.     }
  14.     // selling a vehicle NEVER changes, so this should be marked as a final function so subclasses can implement their own version of it
  15.     final protected function sellVehicle()
  16.     {
  17.         echo __METHOD__ . " selling Vehicle\n";
  18.     }
  19.  
  20.     // we ALWAYS only have the same steps, in the same order, so we can use this method as the template
  21.    // like sellVehicle(), this should never be implemented
  22.    final  public function template()
  23.     {
  24.         echo __METHOD__ . " making a new vehicle from scratch\n";
  25.         $this->addEngine();
  26.         $this->addWheels();
  27.         $this->paintVehicle();
  28.         $this->sellVehicle();
  29.         echo __METHOD__ . " vehicle was made and sold! \n\n---------------\n";
  30.     }
  31. }

That abstract class covers paintVehicle() and sellVehicle(), however addWheels() and addEngine() are only abstract methods so they need to implemented in sub classes.

Please note the use of final, which is important for the template pattern. We don't ever want a subclass implementing their own way of selling a vehicle (but maybe they can do it for painting, there could be some specialised vehicle that needs its own painting procedure)

CarMaker_2.php

(Ignore the bad naming of this class. It is just to make it easier to work out what class I'm talking about)

This subclass must extend the main abstract template class (VehicleMaker). It only needs to implement two methods.

  1. class CarMaker_2 extends VehicleMaker
  2. {
  3.     protected function addWheels()
  4.     {
  5.         echo __METHOD__ . " added 4 car wheels\n";
  6.     }
  7.     protected function addEngine()
  8.     {
  9.         echo __METHOD__ . " added a car engine\n";
  10.     }
  11. }
MotorbikeMaker_2.php

Again please ignore the bad naming of files and classes here. But this class is very similar to CarMaker_2, just with a motorbike engine and wheels instead of car ones.

  1. class MotorbikeMaker_2 extends VehicleMaker
  2. {
  3.     protected function addWheels()
  4.     {
  5.         echo __METHOD__ . " added 2 motorbike wheels\n";
  6.     }
  7.     protected  function addEngine()
  8.     {
  9.         echo __METHOD__ . " added a motorbike engine\n";
  10.     }
  11. }
Putting it all together

And these methods are called with something like this:

  1. $motorbikemaker_2 = new MotorbikeMaker_2;
  2. $motorbikemaker_2->template();
  3.  
  4. $carmaker_2 = new CarMaker_2;
  5. $carmaker_2->template();

When to use the template method in the real world

  • When you end up repeating a lot of the same code, and the code can be split up into similar 'steps' or 'sections'.
  • When you want to be able to extend code easily ("open for extension"), but control the core parts of it ("closed for modification") - in the example above we could easily extend it by adding a new vehicle type, but the selling or actual template making methods should not be changed.
  • When you have a set of steps (algorithm), that might have multiple implementations. The base set of steps (algorithm) will be defined in the base class, but sub classes can create their own implementation of each step that replace the base class steps.

The template method in the real world (examples of the template method)

The above example was a little silly and very basic. However, this method is used all the time in PHP development (and other languages).

They can be used for things such as:

  • Payments - you might have a base class that saves payment info, redirects the user to the payment gateway. However you might have subclasses that have methods for telling the base class which URL to redirect to, and a method for receiving the information from the payment provider (and processing it before sending it to the base methods of saving the new subscription info). So you might have subclasses for Paypal, another one for Stripe subscriptions, etc.
  • Creating invoices - a base class will handle things such as generating and/or getting the invoice. But the subclasses might have different implementations for rendering the invoice. You might have a PDF output class, or a Word Document output class. They will use the base class, but have their own implementation of the actual output.

I think this is one design pattern that almost everyone uses but doesn't know the name of it. As soon as you learn about inheritance you will probably end up doing something like this (maybe without abstract classes, but just normal classes).

webdevetc profile pic
webdevetc

I am a 29 year old freelance backend web developer from London, mostly focusing on PHP and Laravel lately. This is my site - I mostly write about PHP here. Contact me here (especially for any contracting jobs early 2019 in London ;) ).

Leave a Comment