I agree with this method, although many people will tell you that this singleton approach is bad, bad.
However, I do not agree 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; }
In addition, it seems reasonable to move the handler code to the handler (and , of course, without an unconditional echo error!)
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();
In addition, I would expand it to accept a parameter to make several connections possible.
source share