What is the purpose of using a Factory Pattern in PHP and how does it help in organizing code structure?

Using a Factory Pattern in PHP helps in creating objects without specifying the exact class of object that will be created. This allows for more flexible and maintainable code as it decouples the client code from the concrete implementations of objects. It also helps in organizing code structure by centralizing the object creation logic in one place.

<?php

interface Shape {
    public function draw();
}

class Circle implements Shape {
    public function draw() {
        echo "Drawing a circle.";
    }
}

class Square implements Shape {
    public function draw() {
        echo "Drawing a square.";
    }
}

class ShapeFactory {
    public function createShape($shapeType) {
        switch ($shapeType) {
            case 'circle':
                return new Circle();
            case 'square':
                return new Square();
            default:
                throw new \InvalidArgumentException('Invalid shape type.');
        }
    }
}

// Client code
$factory = new ShapeFactory();
$circle = $factory->createShape('circle');
$square = $factory->createShape('square');

$circle->draw(); // Output: Drawing a circle.
$square->draw(); // Output: Drawing a square.

?>