Piszemy Config z prawdziwego zdarzenia dla naszej klasy PDOConnection i nie tylko. Do dzieła.
Po pierwsze, tworzymy (w głównym katalogu) plik config.ini:
; This is a sample configuration file
; Comments start with ';', as in php.ini
[DB_CREDENTIALS]
driver = mysql
host = localhost
db_name = mydb123
db_user = user
db_password = pass
Po drugie, tworzymy klasę ConfigIni:
class ConfigINI {
public static $iniPath = __DIR__ . "/config.ini";
public static function getPDOCredentials(){
$ini_array = parse_ini_file(static::$iniPath, true);
return $ini_array['DB_CREDENTIALS'];
}
}
Teraz możemy jej użyć:
class PDOConnection {
//(...)
public function connect(): PDOConnection{
try {
$this->credentials = ConfigINI::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;
}
//(...)
}
$conn = new PDOConnection();
$conn->connect();
$conn = $conn->getConnection();
Dane zaciągane są stamtąd.