Kolejna rozbudowa klasy PDOConnection do naszego projektu framework MVC. Zaczynajmy!

Najpierw zrobimy sobie „fejkowy” config:

class FakeConfig {

    public static function getPDOCredentials(){
        return [
            'driver' => 'mysql',
            'host' => 'localhost',
            'db_name' => 'mydb123',
            'db_user' => 'user',
            'db_password' => 'pass'
        ];
    }
}

Okej, teraz klasa PDOConnection – pola:

class PDOConnection {

    protected $connection;
    protected $credentials;

    public static $requiredKeys = [
        'driver',
        'host',
        'db_name',
        'db_user',
        'db_password'
    ];

   //(...)

}

Metody pomocnicze:

class PDOConnection {

    //(...)

    public function getConnection(): PDO|null
    {
        return $this->connection;
    }

    public static function parseCredentials($credentials){
        $dsn = sprintf(
            '%s:host=%s;dbname=%s',
            $credentials['driver'],
            $credentials['host'],
            $credentials['db_name']
        );

        return [$dsn, $credentials['db_user'], $credentials['db_password']];
    }

    public static function hasRequiredKeys($credentials){
        foreach(self::$requiredKeys as $key){
            if(!array_key_exists($key, $credentials))
                return false;
        }
        return true;
    }

}

Metoda connect:

class PDOConnection {

    //(...)

    public function connect(): PDOConnection{
        try {
            $this->credentials = FakeConfig::getPDOCredentials();
            if(!static::hasRequiredKeys($this->credentials))
                throw new Error("Credentials dont have valid keys");
            $parsed = static::parseCredentials($this->credentials);
            $this->connection = new PDO(...$parsed);
        } catch (Exception $e) {
            echo $e->getMessage();
        }
        
        return $this;
    }

    //(...)

}

Łączymy się i sprawdzamy, czy działa jak należy:

$conn = new PDOConnection();
$conn->connect();
$conn = $conn->getConnection();