Created
          October 30, 2015 07:37 
        
      - 
      
- 
        Save thoriqmacto/460390655324d57bca42 to your computer and use it in GitHub Desktop. 
    [PHP] Builder Design Pattern Example
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | <?php | |
| 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; | |
| } | |
| } | |
| class ProductBuilder{ | |
| protected $product = NULL; | |
| protected $_configs = array(); | |
| public function __construct($configs){ | |
| $this->product = new Product(); | |
| $this->_configs = $configs; | |
| } | |
| public function build(){ | |
| $this->product->setSize($this->_configs['size']); | |
| $this->product->setType($this->_configs['type']); | |
| $this->product->setColor($this->_configs['color']); | |
| } | |
| public function getProduct(){ | |
| return $this->product; | |
| } | |
| } | |
| // Array of configuration | |
| $productConfigs = array('type' => 'shirt', 'size' => 'XL', 'color' => 'red'); | |
| // OLD WAY - our product configuration received from other functionality | |
| // $product = new product(); | |
| // $product-> setType($productConfigs['type']); | |
| // $product-> setSize($productConfigs['size']); | |
| // $product-> setColor($productConfigs['color']); | |
| // NEW WAY | |
| $builder = new productBuilder($productConfigs); | |
| $builder->build(); | |
| $product = $builder->getProduct(); | |
| echo "<pre>"; | |
| print_r($product); | |
| // var_dump($product); | |
| // print_r($builder); | |
| // var_dump($builder); | |
| echo "</pre>"; | |
| ?> | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment