I programmed a class for database access for my REST service. According to my understanding it should be implemented as singleton, because there can be a lot of simultaneous requests. Is there everything okay with this approach?
Is there a way to handle the getData...
functions better? They basically do all the same thing, expect for the SQL query and the different parameters for the query.
Is it good to store the connection data (username, password..) in a JSON file?
Note that I've modified some lines from the actual code (SQL-queries and function names), because I think they are not relevant for my questions.
class DBManager {
protected static $con;
protected static $_instance = null;
protected function __construct() {
$data = self::getConnectionData ();
$host = $data ["host"];
$name = $data ["name"];
self::$con = new PDO ( "pgsql:host=$host;dbname=$name", $data ["user"], $data ["password"] );
}
protected function __clone() {}
public static function getInstance() {
if (null === self::$_instance) {
self::$_instance = new self ();
}
return self::$_instance;
}
protected function getConnectionData() {
$raw = file_get_contents ( "conf/database.json" );
$json = json_decode ( $raw, true );
return $json;
}
public function getData1($year) {
$query = "...";
$stmt = self::$con->prepare ( $query );
$stmt->bindParam ( 1, $year );
$stmt->execute ();
$result = $stmt->fetchAll ( PDO::FETCH_ASSOC );
return $result;
}
public function getData2($year, $month) {
$query = "...";
$stmt = self::$con->prepare ( $query );
$stmt->bindParam ( 1, $year );
$stmt->bindParam ( 2, $month);
$stmt->execute ();
$result = $stmt->fetchAll ( PDO::FETCH_ASSOC );
return $result;
}
// more getData functions...
}
try/catch
around your connection as this is standard practice - for example: github.com/sbebbers/FrameWork.php/blob/master/application/model/… - though this is creating a custom exception from the PDO exception; you could replace this withecho '<pre>' . print_r($e, 1) . '</pre>';
instead so that you have some visual indication of what has gone wrong, at least whilst you are in development. Don't deploy thisecho
ing out thePDOException
to a live website; instead write the issue to a log file (as happens in the link if you trace it back) \$\endgroup\$