How can the Factory Pattern be utilized in PHP to instantiate objects for different levels of an organizational hierarchy?

The Factory Pattern can be utilized in PHP to instantiate objects for different levels of an organizational hierarchy by creating a factory class that determines which subclass to instantiate based on certain criteria. This allows for flexibility in creating objects without tightly coupling the client code to specific subclasses.

<?php

// Abstract class representing the organizational hierarchy
abstract class Employee {
    protected $name;

    public function __construct($name) {
        $this->name = $name;
    }

    abstract public function getRole();
}

// Concrete classes representing different levels of the organizational hierarchy
class Manager extends Employee {
    public function getRole() {
        return "Manager";
    }
}

class Supervisor extends Employee {
    public function getRole() {
        return "Supervisor";
    }
}

// Factory class to instantiate objects based on the organizational hierarchy level
class EmployeeFactory {
    public static function createEmployee($name, $level) {
        switch ($level) {
            case 'Manager':
                return new Manager($name);
            case 'Supervisor':
                return new Supervisor($name);
            default:
                throw new Exception("Invalid employee level");
        }
    }
}

// Client code
$manager = EmployeeFactory::createEmployee("John Doe", "Manager");
$supervisor = EmployeeFactory::createEmployee("Jane Smith", "Supervisor");

echo $manager->getRole() . ": " . $manager->name . PHP_EOL;
echo $supervisor->getRole() . ": " . $supervisor->name . PHP_EOL;

?>