Reputation: 10974
I'm using this function to connect to my MySQL db when needed, and also to re-use the same connection object for any further query I might need in the same php script.
function cnn() {
static $pdo;
if(!isset($pdo)) {
try {
$pdo = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
$pdo->setAttribute(PDO::ATTR_TIMEOUT, 30);
$pdo->setAttribute(PDO::ATTR_PERSISTENT, true);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_OBJ);
return $pdo;
} catch(PDOException $e) {
http_response_code(503);
echo $e->getCode.': '.$e->getMessage();
die(); //or whatever error handler you use
}
} else {
return $pdo;
}
}
First query (object is created)
echo cnn()->query('SELECT firstname FROM user WHERE id=4;')->fetch(PDO::FETCH_COLUMN)
Second query (object is reused)
echo cnn()->query('SELECT title FROM news WHERE id=516;')->fetch(PDO::FETCH_COLUMN)
Do you agree on this approach? Do you think it can be optimized? Thanks for your opinions.
Upvotes: 4
Views: 2966
Reputation: 157862
I agree with the method, though many people will tell you that this "singleton" approach is bad, bad.
However, I disagree with your implementation. It should be:
function cnn() {
static $pdo;
if(!$pdo) {
$conf = array(PDO::ATTR_TIMEOUT => 30,
PDO::ATTR_PERSISTENT => true,
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
);
$dsn = 'mysql:host='.DB_HOST.';dbname='.DB_NAME;
$pdo = new PDO($dsn, DB_USER, DB_PASS, $conf);
}
return $pdo;
}
Also, it looks sensible to move handler code into handler (and of course without echoing the error unconditionally!)
function my_exceptionHandler($exception) {
http_response_code(503);
if (ini_get('display_errors')) {
echo $e->getMessage().$e->getTrace();
} else {
log_error($e->getMessage().$e->getTrace());
}
die(); //or whatever error handler you use
}
set_exception_handler("my_exceptionHandler");
Also, I'd extend it to accept a parameter to make several connections possible.
Upvotes: 3