Ejemplo n.º 1
0
 /**
  * Connect to the Mongo database.
  */
 function connect()
 {
     /*
     Parse config->mongo for connection params.
     	
     	example yml:
     	  mongo:
     	    [{database}:]
     	      user: {username}
     	      pass: {password}
     	      [database: {database}]
     	      [host: {host}]
     	      [debug: {true|false|1|2}]
     	      [log: {true|false}]
     	    ...
     */
     if (!self::$db_params) {
         self::$db_params = array();
         $default_params = array();
         foreach ((array) Request::$config->mongo as $key => $value) {
             if (is_array($value) && $value['user'] && $value['pass'] && $value['database']) {
                 self::$db_params[$key] = $value;
             } else {
                 $default_params[$key] = $value;
             }
         }
         if (!empty($default_params)) {
             self::$db_params['default'] = $default_params;
         }
     }
     // Select connection params by 'database' key.
     $this->params = array_merge((array) $this->params, (array) ($this->database ? self::$db_params[$this->database] : self::$db_params['default']));
     // Remember chosen database.
     $this->database = $this->params['database'];
     // Re-usable database handle.
     $this->dbh =& self::$mongo[$this->database];
     // Need to setup mongo instance?
     if ($this->dbh instanceof MongoDB == false) {
         // Default params.
         $host = $this->params['host'] ?: 'localhost';
         $port = $this->params['port'] ?: 27017;
         $options = $this->params['options'] ?: array();
         // Default database name.
         $this->database = $this->database ?: 'default';
         // Username and password?
         if ($this->params['user'] && $this->params['pass']) {
             $userpass = "******";
             // Hide password.
             unset($this->params['pass']);
         }
         // Connect to Mongo.
         $mongo_class = class_exists('MongoClient') ? 'MongoClient' : 'Mongo';
         $mongo = new $mongo_class("mongodb://{$userpass}{$host}:{$port}/{$this->database}", $options);
         // Get the database handle.
         $this->dbh = $mongo->selectDB($this->database);
     }
     // Shortcut to the mongo collection.
     $this->dbc = $this->dbh->{$this->collection};
     // Ensure indexes.
     $this->ensure_indexes($this->indexes);
 }