PHP Design Patterns

PHP Design Patterns

Design patterns are proven, reusable solutions to common programming problems. Here are the most useful patterns in PHP.

1 - Singleton

class Database {
    private static ?self $instance = null;

    private function __construct(private readonly PDO $pdo) {}

    public static function getInstance(): self {
        if (self::$instance === null) {
            $pdo = new PDO("mysql:host=localhost;dbname=app", "root", "");
            self::$instance = new self($pdo);
        }
        return self::$instance;
    }

    public function getPdo(): PDO { return $this->pdo; }
}

2 - Factory

interface Storage {
    public function put(string $key, string $data): void;
    public function get(string $key): ?string;
}

class FileStorage implements Storage { /* ... */ }
class RedisStorage implements Storage { /* ... */ }

class StorageFactory {
    public static function make(string $driver): Storage {
        return match ($driver) {
            "file"  => new FileStorage(),
            "redis" => new RedisStorage(),
            default => throw new InvalidArgumentException("Unknown driver: $driver")
        };
    }
}

$storage = StorageFactory::make("redis");

3 - Observer

interface Listener {
    public function handle(string $event, mixed $payload): void;
}

class EventEmitter {
    private array $listeners = [];

    public function listen(string $event, Listener $l): void {
        $this->listeners[$event][] = $l;
    }

    public function emit(string $event, mixed $payload = null): void {
        foreach ($this->listeners[$event] ?? [] as $l) {
            $l->handle($event, $payload);
        }
    }
}

Note: Apply patterns when they solve a real problem, not to appear clever. Over-engineering a small script with the full Gang-of-Four catalogue is a well-known anti-pattern called "architecture astronautics".

-Tip-