How to implement the Builder design pattern in PHP for complex object creation?

by raphael_tillman , in category: PHP General , 2 years ago

How to implement the Builder design pattern in PHP for complex object creation?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by samara , 2 years ago

@raphael_tillman 

The Builder design pattern is used to create complex objects by separating the object construction process from its representation. This pattern is useful when we want to create an object that requires several steps to be completed or when we want to create an object with optional or default parameters. Here's an example of how to implement the Builder design pattern in PHP:

  1. First, we need to create an interface that defines the methods for building the object:
1
2
3
4
5
6
interface BuilderInterface {
    public function setPartA($value);
    public function setPartB($value);
    public function setPartC($value);
    public function getResult();
}


  1. Next, we create a concrete builder class that implements the interface:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class ConcreteBuilder implements BuilderInterface {
    private $product;

    public function __construct() {
        $this->product = new Product();
    }

    public function setPartA($value) {
        $this->product->setPartA($value);
        return $this;
    }

    public function setPartB($value) {
        $this->product->setPartB($value);
        return $this;
    }

    public function setPartC($value) {
        $this->product->setPartC($value);
        return $this;
    }

    public function getResult() {
        return $this->product;
    }
}


  1. Now, we create a director class that is responsible for using the builder to construct the object:
1
2
3
4
5
6
7
8
9
class Director {
    public function build(BuilderInterface $builder) {
        return $builder
            ->setPartA('Part A')
            ->setPartB('Part B')
            ->setPartC('Part C')
            ->getResult();
    }
}


  1. Finally, we can use the builder and the director to create the object:
1
2
3
$builder = new ConcreteBuilder();
$director = new Director();
$product = $director->build($builder);


In this example, the ConcreteBuilder class is responsible for constructing the Product object, the Director class is responsible for using the builder to construct the object, and the Product class is the complex object that we want to create. The builder separates the object construction process from its representation, allowing us to create objects with optional or default parameters.