1

Could someone tell me whether the following is A) a good solution to the problem of repeating code and B) an example of the template method?

Let's say I have one table, named VEHICLES, which I use to store different types of vehicles (e.g. car, van, bus). I have a bunch of repository classes which should retrieve each type of vehicle:

class CarRepository{
  public function getAll(){
    $sql = "select * from vehicles where type='car'";
    //some code to communicate with the database
  }
}

class BusRepository{
  public function getAll(){
    $sql = "select * from vehicles where type='bus'";
    //some code to communicate with the database
  }
}

As you can see, each repo has almost the same code in the getAll method, which isn't very DRY. I was thinking a better solution might be to have a common base class for the repos, like this:

abstract class VehicleRepository{
  final public function getAll(){
    $sql = "select * from vehicles where type='".$this->getType()."'";
    echo $sql;
    //code to communicate with the database
  }

  abstract function getType();
}

And then each repo would just need to define the getType method:

class CarRepository extends VehicleRepository{
    public function getType(){
        return "car";
    }
}

class BusRepository extends VehicleRepository{
    public function getType(){
        return "bus";
    }
}

Does this seem reasonable? And is this what is meant by the template method pattern?

1 Answers1

1
  1. Yes, that is the template method pattern

  2. Currently there is no need to make the getType methods public, "protected" would be enough. If you actually need them outside of that class hierarchy, you can make them public, of course.

Doc Brown
  • 206,877