static function getInstance() { if (null === self::$_instance) { // создаем новый экземпляр self::$_instance = new self(); } // возвращаем созданный или существующий экземпляр return self::$_instance->dbh; }
/** * Get a connection from pool * * @param string $connection * @return \PDO * @throws \Exception */ public static function get($connection = '') { $configFile = self::$_configFile; if (defined('APP_ENV')) { $configFile = APP_ENV . '.' . self::$_configFile; } //get the connections if (is_file(CONFIG_DIR . $configFile) && empty(self::$config)) { self::$config = (include CONFIG_DIR . $configFile); } //if connection not exists then create it if (!isset(self::$pool[$connection])) { if (isset(self::$config) && !empty(self::$config)) { if (isset(self::$config[$connection]) && !empty(self::$config[$connection])) { if (isset(self::$config[$connection]['dsn']) && !empty(self::$config[$connection]['dsn'])) { if (isset(self::$config[$connection]['user']) && !empty(self::$config[$connection]['user'])) { if (isset(self::$config[$connection]['pass']) && !empty(self::$config[$connection]['pass'])) { //if no options just add an empty array if (!isset(self::$config[$connection]['options'])) { self::$config[$connection]['options'] = array(); } //create the connection try { self::$pool[$connection] = new \PDO(self::$config[$connection]['dsn'], self::$config[$connection]['user'], self::$config[$connection]['pass'], self::$config[$connection]['options']); //some attributes self::$pool[$connection]->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); self::$pool[$connection]->setAttribute(\PDO::ATTR_ORACLE_NULLS, \PDO::NULL_EMPTY_STRING); } catch (\PDOException $e) { throw new \Exception('ERROR - Could not connect to database.', 15); } } else { //pass parameter not found throw new \Exception('ERROR - "pass" parameter not found.', 14); } } else { //user paramter not found throw new \Exception('ERROR - "user" parameter not found.', 13); } } else { //dsn parameter not found throw new \Exception('ERROR - "dsn" parameter not found.', 12); } } else { //connection passed in parameter not found throw new \Exception('ERROR - Connection "' . $connection . '" not found.', 11); } } else { //empty config throw new \Exception('ERROR - Empty database config file.', 10); } } return self::$pool[$connection]; }
/** * init PDO db handler */ public static function init() { $config = (include APP_PATH . '..' . DS . 'config' . DS . 'db.php'); self::$table_prefix = $config['table_prefix']; $connection_string = 'mysql:host=' . $config['host'] . ';port=' . $config['port'] . ';dbname=' . $config['db']; $options = array(\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); try { self::$dbh = new \PDO($connection_string, $config['user'], $config['password'], $options); self::$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION); } catch (\PDOException $e) { echo "Connection failed: " . $e->getMessage(); die; } }