4.3. Code Example
The project contains a class that creates the complex product object. This class contains three methods to completely form it. If each of these methods is not called when creating a new product object, attributes of the class will be missing and the program will halt. These methods are setType(), setColor(), and setSize(). The initial version of this code was designed to create the object followed by the execution of each of these methods.
class product
{
protected $_type = '';
protected $_size = '';
protected $_color = '';
public function setType($type)
{
$this->_type = $type;
}
public function setSize($size)
{
$this->_size = $size;
}
public function setColor($color)
{
$this->_color = $color;
}
}
To create a complete product object, the product configurations need to be passed individually to each of the methods of the product class:
// our product configuration received from other functionality
$productConfigs = array('type'=>'shirt', 'size'=>'XL', 'color'=>'red');
$product = new product();
$product->setType($productConfigs['type']);
$product->setSize($productConfigs['size']);
$product->setColor($productConfigs['color']);
Having to call each one of these methods when an object is created is not best practice. Instead, an object based on the Builder Design Pattern should be used to create this product instance.
The productBuilder class is designed to accept those configuration options that are required to build the product object. It stores both the configuration ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access