Demonstrating Builder Design Pattern in PHP

One of the other design patterns is the Builder Pattern and this pattern belongs to the Creational patterns that is used to create objects in addition to that it will prepare the object for the application too.


Builder Pattern

From wikipedia the builder pattern:

The intent of the Builder design pattern is to separate the construction of a complex object from its representation

In other terms unlike the traditional creational patterns like Factory and Singletoon, which tend to create a new empty instance of the object, the Builder create a fully prepared object ready for specific task.An example of this is to create a setup engine for specific software.

Builder pattern flowchart


So the problem is we need a way to create an object with a set of functions already prepared, let’s see an example, imagine we have a Vehicle class and we need to create different implementations of this class using the builder pattern.


A typical Builder consists of:

  • Concrete class
  • A builder interface
  • The different builder implementations
  • A director class that calls the appropriate builder and return it.


Concrete class (Vehicle)


Builder interface

As shown in the above code the Builder interface contains methods for preparing the builder when created and method getVehicle will return the final object.


Builder implementations

As you see above we just created some implementations of the Builder interface passing the original concrete class in every constructor, then we implemented the helper functions such as setModel, and setType which in turn will provide a full qualified object, finally we called getVehicle to return the Vehicle object like this:


Now the final piece is the director class, the main responsibility of the director is to get a builder interface and call the builder methods then retrieve the object.


Now to use the builder:


If you output the any of these instances for example the $kiaCar you will get an instance of Vehicle with attributes prepared for the kia car.


Someone might ask why we use the builder pattern instead we can get a similar behavior if you provide to our constructor the required parameters and get the same result, and the answer is that as we mentioned in the beginning of the article that there are some cases that we need to get a full qualified object in just one line of code without going with all the required steps of initialization, setting attributes and calling methods. 



Share this: