It works great if the connection is valid, but it seems PDOException doesn't actually work if the connection fails. The catch totally fails to execute. If its fails, it break execution of this line $this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);
. So i can't get PDOException in catch block. How do I keep get this to work?
<?php
namespace app\Helpers;
use \PDO;
/**
* Core class which exists only once through the application
*
*/
class Core
{
public $dbh; // handle of the db connexion
private static $instance;
// constructor to create a MySQLi instance (="MySQL Improved Extension")
private function __construct()
{
$db_host = ConfigHelper::read('db.host');
$db_name = ConfigHelper::read('db.basename');
$db_user = ConfigHelper::read('db.user');
$db_pass = ConfigHelper::read('db.password');
$db_driver = ConfigHelper::read('db.driver');
try {
$this->dbh = new PDO("$db_driver:host=$db_host;dbname=$db_name", $db_user, $db_pass);
} catch (PDOException $pdoex) {
exit("Database connection failed: " . $pdoex->getMessage());
return false;
}
}
/**
* get instance of Core object
*
* @return Object self
*/
public static function getInstance()
{
if (!isset(self::$instance)) {
$object = __CLASS__;
self::$instance = new $object;
}
return self::$instance;
}
}
It is a namespace issue.
When within a namespace, you have to address every root level class name by prepending it with a backslash.
But you didn't.
But the worst part is that you should not catch a PDOException at all. Just leave it alone and let it report to a site-wide report handler