I have two db and i want to return one of them from my Db class which is actually Singleton pattern. So i don't want to make new connections every time but to check if connection exists in array and then to return it. The problem is that only thing that i am returning from getInstance method is same Db object and not PDO object?
class Db
{
public static $dbTypes = [];
/**
* Db constructor.
* @param $db
*/
private function __construct($db)
{
switch ($db) {
case ConfigManager::getDbDatabase(true):
try {
self::$dbTypes[$db] = new \PDO("mysql:host=" . ConfigManager::getDbHost(true) . ";dbname=" . ConfigManager::getDbDatabase(true) . ";charset=utf8", ConfigManager::getDbUser(true), ConfigManager::getDbPass(true));
} catch (\PDOException $ex) {
echo $ex->getMessage();
}
break;
case ConfigManager::getDbDatabase(false):
try {
self::$dbTypes[$db] = new \PDO("mysql:host=" . ConfigManager::getDbHost(false) . ";dbname=" . ConfigManager::getDbDatabase(false) . ";charset=utf8", ConfigManager::getDbUser(false), ConfigManager::getDbPass(false));
} catch (\PDOException $ex) {
echo $ex->getMessage();
}
break;
}
}
/**
* @throws \Exception
*/
private function __clone()
{
throw new \SoapFault('CODE_ERROR', 'You can not clone ' . __CLASS__ . ' class.');
}
/**
* @param $db
* @return \PDO
*/
public static function getInstance($db) : \PDO
{
if (!array_key_exists($db, self::$dbTypes)) {
self::$dbTypes[$db] = new self($db);
}
return self::$dbTypes[$db];
}
}
Don't let ConfigManager class confuse you, it is just a getter class to fetch values from config file. Basically if param in ConfigManager methods is true values for first db are being returned and if it is false then values for second db are being returned. And i want to use PDO like this:
$this->db = Db::getInstance(ConfigManager::getDbDatabase(true));
$query = $this->db->prepare("SELECT c.extern_username...
I am getting "Call to undefined method Helpers\ConfigHelpers\Db::prepare()" error. Please advise.
Aucun commentaire:
Enregistrer un commentaire