📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PHP for Beginners Design Patterns — Factory

Design Patterns — Factory

5 min read
Factory creates objects without specifying the exact class upfront. A factory method returns the right implementation based on a parameter. Useful for payment gateways, email transports, and other swappable components.

Factory Pattern

interface Logger {
    public function log(string $message): void;
}

class FileLogger implements Logger {
    public function log(string $message): void {
        file_put_contents("app.log", $message . "\n", FILE_APPEND);
    }
}

class DatabaseLogger implements Logger {
    public function log(string $message): void {
        // insert into logs table
    }
}

class LoggerFactory {
    public static function create(string $type): Logger {
        return match($type) {
            "file"     => new FileLogger(),
            "database" => new DatabaseLogger(),
            default    => throw new InvalidArgumentException("Unknown logger: $type")
        };
    }
}

$logger = LoggerFactory::create($_ENV["LOG_DRIVER"]);
$logger->log("App started");