How can the Registry pattern be effectively implemented in PHP classes for database connections?

The Registry pattern can be effectively implemented in PHP classes for database connections by creating a central registry class that stores and manages database connection instances. This allows for easy access to the database connection throughout the application without the need to repeatedly create new instances.

class DatabaseRegistry {
    private static $connections = [];

    public static function setConnection(string $name, PDO $connection) {
        self::$connections[$name] = $connection;
    }

    public static function getConnection(string $name): PDO {
        if(isset(self::$connections[$name])) {
            return self::$connections[$name];
        } else {
            throw new Exception("Connection '$name' not found in registry.");
        }
    }
}

// Usage example
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
DatabaseRegistry::setConnection('default', $pdo);

// Retrieve connection
$pdo = DatabaseRegistry::getConnection('default');