Skip to content
PHP Logo

How can the Factory design pattern be applied to improve the handling of object instantiation and class mutation in PHP?

The Factory design pattern can be applied to improve the handling of object instantiation and class mutation in PHP by centralizing the creation of objects in a separate factory class. This allows for better encapsulation and flexibility, as the factory class can handle the instantiation logic based on certain criteria or configurations.

php
<?php

// Factory class to create objects based on type
class ShapeFactory {
    public static function createShape($type) {
        switch($type) {
            case 'circle':
                return new Circle();
            case 'square':
                return new Square();
            default:
                throw new Exception("Invalid shape type");
        }
    }
}

// Example classes representing different shapes
class Circle {
    public function draw() {
        echo "Drawing a circle";
    }
}

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

// Create objects using the factory
$circle = ShapeFactory::createShape('circle');
$circle->draw();

$square = ShapeFactory::createShape('square');
$square->draw();