The Factory Pattern in PHP 5

-

Introduction

The factory is one of the most common OOP patterns. The concept of the factory pattern is pretty straight forward. The factory pattern uses a class that has methods that create objects rather than creating the objects directly

Example Factory Patttern

<?php
  class Circle {
    private $sides;
    public function __construct(){
      $this->sides = 1;
    }
  }  
  class Triangle {
    private $sides;
    public function __construct(){
      $this->sides = 3;
    }
  }
  class Square {
    private $sides;
    public function __construct(){
      $this->sides = 4;
    }
  }
?>

 Instead of just instantiating the class directly below: 

<?php
  $mySquare = new Square;
?>

 You would make another class (this is where the factory part comes in): 

<?php
  class Shape {
    public function build($type){
      switch ($type) {
        case 'square':
          include_once 'Square.php';
          return new Square;
          break;
        case 'triangle':
          include_once 'Triangle.php';
          return new Triangle;
          break;
        case 'circle':
          include_once 'Circle.php';
          return new Circle;
          break;
      }
    }
  }  
?>

you would use the above class by: 

<?php
  $shapeFactory = new Shape();
  $myShape = $shapeFactory->build(‘triangle’);
?>

Your comments.