Builder Pattern

Today we'll be discussing the Builder pattern. Another someone simplistic pattern to use. As you might've guessed by the name of the pattern, this one usually deals with handling object creation. Particularly objects with complex business logic attached to it and need to be prepared in a certain way before they can be used. All instantiation logic must be handled in the Builder class and returned from the Builder class. I will provide some examples below.

Let's start with the actually builder:

class CarBuilder {
  private $_car = NULL;
  private $_attributes = [];
 
  public function __construct($attributes) {
    $this->_car = new Car();
    $this->_attribuets = $attributes;
  }

  public function build() {
    $this->_car->setMaker($attributes['make']);
    $this->_car->setYear($attributes['year']);
    return $this->_car;
 }
}

For this example I'm using a simple car analogy. Nothing too complex. The main take-away here is that your "Builder" class will typically handle the creation and instantiation of said object and will return it when asked. You can add all sorts of different methods related to different attributes of said car. I go won't too far into detail as that's related to more discussions specific to OOP itself and not patterns.

The Car class might look something like this:

class Car {

	private $make;
	private $year;

	public function setMaker($make) {
		$this->make = $make;
	}

	public function setYear($year) {
		$this->year = $year;
	}

	//... Add other setter/getters

}

 

Nothing special. Now, to actually use the builder you'd do something like this:

$car_builder = new CarBuilder([
"make" => "Chevy",
"year" => 2017,
]);

$car = $car_builder->buid();

You basically relegate all your logic to the production of your object to the builder. So that in case within the future there is a change in the requirements regarding the object you would need to update your builder rather than all over your code base where the object is used.

This is just a very simple example. You could improve it quite a bit by using some more advanced/clever techniques but this is a start.