Introduction to Builder design pattern in PHP

The Builder Pattern is a software design pattern which helps to simplify creation of complex objects by reducing the number of parameters in the object constructor.
This pattern uses a builder object to collect parameters of the complex object and return the final constructed object.

Problem:

Imagine we have a car object with many attributes.
The following is the class definition and object instantiation code:

As you can see everything we want to create a Car object we have to pass all those attribute to the constructor.
In addition, What if we want to skip over some attributes and use the default value? For instance, we want to have default value of ‘Sedan’, ‘Petrol’, and ‘4’ for bodyType, fuelType, and cylinders respectively.
The constructor would look like :

But how would our object instantiation look like?

Solution: Builder Pattern

Instead of instantiating Car object directly we create a builder object called CarBuilder and let that handle our object creation:

Advantages:

  • Clean and easier to read code
  • Decoupled and more encapsulated code (have you noticed the use of Factory Pattern inside build() function?)
  • You can easily skip attributes that are not needed for specific objects and use the default value instead.
  • Avoiding too many arguments in the constructor

Disadvantages:

  • It requires writing more code