public function __construct(\Lib\DbConfig $dbConfig) { $maxTry = 3; $index = 1; \Lib\State::notice('Connecting to MySQL...'); while ($index <= $maxTry) { \Lib\State::notice('Try ' . $index . '...'); $index++; try { $pdo = new \PDO($dbConfig->getDsn(), $dbConfig->getUsername(), $dbConfig->getPasswd()); } catch (\Exception $e) { \Lib\State::warning($e->getMessage()); if ($index <= $maxTry) { \Lib\State::notice('Try to connect again after 3 seconds'); sleep(3); } continue; } break; } if (!isset($pdo) || !$pdo instanceof \PDO) { \Lib\State::notice($dbConfig->toString()); \Lib\State::error('MySQL connection failed.'); } $options = $dbConfig->getOptions(); if (!empty($options)) { foreach ($options as $option) { $pdo->query($option); } } \Lib\State::notice('connect successed'); $this->_db = $pdo; $this->_dbname = $dbConfig->getDbname(); }
/** * 获取 DB 资源 * * @return Db */ protected function getDbResponse() { if (!$this->_db instanceof \Lib\Db) { $options = \Lib\Options::getInstance(); $dbConfig = \Lib\DbConfig::getInstance(); $userName = $options->getUsername(); $passwd = $options->getPasswd(); $confName = empty($userName) || empty($passwd) ? $options->getDbConfig() : false; $params = array('host', 'dbname', 'port', 'options'); if (!empty($confName)) { $predefined = '\\Config\\' . ucfirst(strtolower($confName)); $preConfig = new $predefined(); if ($preConfig instanceof \Config\ConfigAbstract) { $dbConfig->setHost($preConfig->get('host')); $dbConfig->setPort($preConfig->get('port')); $dbConfig->setDbname($preConfig->get('dbname')); $dbConfig->setOptions($preConfig->get('options')); $dbConfig->setUsername($preConfig->get('username')); $dbConfig->setPasswd($preConfig->get('passwd')); } } else { array_push($params, 'username'); array_push($params, 'passwd'); } foreach ($params as $name) { $get = 'get' . ucfirst(strtolower($name)); if (method_exists($options, $get)) { $val = $options->{$get}(); $set = 'set' . ucfirst(strtolower($name)); if (!empty($val) && method_exists($dbConfig, $set)) { $dbConfig->{$set}($val); } } } $this->_db = new \Lib\Db($dbConfig); $this->_dbname = $dbConfig->getDbname(); } return $this->_db; }