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;
}
}