示例#1
0
 public static function setConfig($config)
 {
     if (empty($config)) {
         throw new Exception('config array empty');
     }
     $config = array_merge(array('host' => 'localhost', 'username' => 'root'), $config);
     if (!empty(self::$config)) {
         // 只准运行一次
         throw new Exception('db can be set config only once');
     }
     if (isset($config['force']) && $config['force'] === 'master') {
         self::$forceMaster = true;
     }
     // username and password
     if (isset($config['username'])) {
         $username = $config['username'];
     } else {
         throw new Exception('config no username');
     }
     if (isset($config['password'])) {
         $password = $config['password'];
     }
     if (isset($config['pwd'])) {
         $password = $config['pwd'];
     }
     if (!isset($config['password']) && !isset($config['pwd'])) {
         throw new Exception('config no password');
     }
     // first look for dsn
     if (isset($config['dsn'])) {
         $dsn = $config['dsn'];
         if (isset($config['dsn_s'])) {
             $dsn_s = $config['dsn_s'];
         }
     }
     // then look for master or slave or no
     if (isset($config['host'])) {
         $conf['host'] = $config['host'];
     }
     if (isset($config['port'])) {
         $conf['port'] = $config['port'];
     }
     if (isset($config['dbname'])) {
         $conf['dbname'] = $config['dbname'];
     }
     if (isset($config['master'])) {
         $master = array_merge($conf, $config['master']);
     } else {
         $master = $conf;
     }
     if (isset($config['slave'])) {
         $slave = array_merge($conf, $config['slave']);
     } else {
         $slave = $conf;
     }
     $dsn = self::makeDsn($master);
     $dsn_s = self::makeDsn($slave);
     $config = compact('dsn', 'dsn_s', 'username', 'password');
     self::$config = $config;
 }