I Want to improve my knowledge about PHP Pattern and Architecture. I create a stupid example to use Factory Pattern
This is my Code:
index.php
$shape = Shape::getShape('circle', 3);
echo $shape->getArea();
shapes.php
class Shape
{
public static function getShape($type, $num)
{
switch ($type) {
case 'circle':
return new Circle($num);
break;
case 'square':
return new Square($num);
break;
default:
throw new Exception("Unrecognized shape");
}
}
}
abstract class Form{
abstract public function getArea();
}
class Circle extends Form{
protected $_type = "Circle";
private $area;
/**
* circle constructor.
* @param $area
*/
public function __construct($area)
{
$this->area = $area;
}
public function getArea(){
return $this->area*pi();
}
}
Where is the advanteges to use this approach ?
I could do it, to create Circle Object
$circle = new Circle(3);
echo $circle->getArea();
The Only Advantage that I can see with use Factory Pattern is that, I could don't know which Shape the user Want.
With a simplistic example like yours, there aren't any real benefits; but a real factory will typically apply the business logic to determine what class to instantiate rather than you telling it what class you want it to return.
In your example, you're specifically saying what shape you want, and it then it simply returns an object of the appropriate type; but suppose you only knew how many corners you had, and passed that number of corners to the factory, then it could determine what shape object to return.... you've moved the logic of knowing that 3 corners means a triangle, 4 corners means a square, etc to the factory.
That's still an over-simplistic example, but perhaps demonstrates at leat one benefit of the factory pattern.
A factory can also handle dependency injection to your objects: the factory should know the dependencies, while the calling code doesn't have access to the dependencies, or even know what they might be, and so would be incapable of instantiating the required class on its own.