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");