PHP Template Method Pattern and Class Hierarchies

You can tell when you are not using class hierarchies when you start duplicating fields and methods. By cutting and pasting methods, if there was a defect in the Person class, there would most likely be a defect in the Employee class as well because the implementation was copied between the two.

class Person
{
    private $name;

    public function setName($name)
    {
        $this->name = $name;
    }
}

class Employee
{
    private $name;

    public function setName($name)
    {
        $this->name = $name;
    }
}

Template Method Pattern

The Template Method Pattern is a behavioral design pattern that allows you to defines a skeleton of an algorithm in a base class and let subclasses override the steps without changing the overall algorithm’s structure. This also leverages inheritance. Inheritance allows functionality to be built up from related classes. Each class provides specialized support that’s specific to a class’s purpose. It’s common that functionality in an object-oriented application is provided by class hierarchies rather than single, unrelated classes.

name = $name;
    }

    /**
    * The optional method should by default do nothing.
    */    
    abstract public function introduceSelf();

}

class Person extends PersonTemplate
{
    public function introduceSelf()
    {
        echo 'I am a...';
    }
}

class Employee extends PersonTemplate
{
    public function introduceSelf()
    {
        echo 'My job is a...';
    }
}

function getWho(PersonTemplate $e){
	$e->introduceSelf();
}
$employee = new Employee();
$person = new Person();

getWho($employee);
getWho($person);