Kontynuujemy zagadnienia bazodanowe dla naszego projektu MVC. Dodajemy kolejną metodę – hasRequiredKeys. Do dzieła.
Kod z lekcji poprzedniej:
<?php
class PDOCredentialsParser {
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']];
}
}
$credentials = [
'driver' => 'mysql',
'host' => 'localhost',
'db_name' => 'mydb123',
'db_user' => 'user',
'db_password' => 'pass'];
$parsedCredentials = PDOCredentialsParser::parseCredentials($credentials);
try {
$dbh = new PDO(...$parsedCredentials);
echo "OK!";
} catch (PDOException $e) {
echo "ERROR";
}
?>
Dodajemy pole requiredKeys:
class PDOCredentialsParser {
public static $requiredKeys = [
'driver',
'host',
'db_name',
'db_user',
'db_password'
];
//(...)
}
Teraz metoda hasRequiredKeys:
class PDOCredentialsParser {
//(...)
public static function hasRequiredKeys($credentials){
foreach(self::$requiredKeys as $key){
if(!array_key_exists($key, $credentials))
return false;
}
return true;
}
}
Sprawdzamy, jak do działa:
$credentials1 = [
'driver' => 'mysql',
'host' => 'localhost',
'db_name' => 'mydb123',
'db_user' => 'user',
'db_password' => 'pass'
];
var_dump(PDOCredentialsParser::hasRequiredKeys($credentials1));
//true
$credentials2 = [
'driver' => 'mysql',
'host' => 'localhost',
];
var_dump(PDOCredentialsParser::hasRequiredKeys($credentials2));
//false
Będziemy to jeszcze rozbudowywać.