lithium\data\source\MongoDb::connect PHP Method

connect() public method

Connects to the Mongo server. Matches up parameters from the constructor to create a Mongo database connection.
See also: lithium\data\source\MongoDb::__construct()
public connect ( ) : boolean
return boolean Returns `true` the connection attempt was successful, otherwise `false`.
    public function connect()
    {
        if ($this->server && $this->server->getConnections() && $this->connection) {
            return $this->_isConnected = true;
        }
        $cfg = $this->_config;
        $this->_isConnected = false;
        $host = is_array($cfg['host']) ? join(',', $cfg['host']) : $cfg['host'];
        $login = $cfg['login'] ? "{$cfg['login']}:{$cfg['password']}@" : '';
        $connection = "mongodb://{$login}{$host}" . ($login ? "/{$cfg['database']}" : '');
        $options = array('connect' => true, 'connectTimeoutMS' => $cfg['timeout'], 'replicaSet' => $cfg['replicaSet']);
        try {
            if ($persist = $cfg['persistent']) {
                $options['persist'] = $persist === true ? 'default' : $persist;
            }
            $server = $this->_classes['server'];
            $this->server = new $server($connection, $options);
            if ($prefs = $cfg['readPreference']) {
                $prefs = !is_array($prefs) ? array($prefs, array()) : $prefs;
                $this->server->setReadPreference($prefs[0], $prefs[1]);
            }
            if ($this->connection = $this->server->{$cfg['database']}) {
                $this->_isConnected = true;
            }
        } catch (Exception $e) {
            throw new NetworkException("Could not connect to the database.", 503, $e);
        }
        return $this->_isConnected;
    }

Usage Example

Ejemplo n.º 1
0
 public function testGoodConnectionBadDatabase()
 {
     $db = new MongoDb(array('database' => null, 'autoConnnect' => false));
     $this->assertException('Could not connect to the database.', function () use($db) {
         $db->connect();
     });
 }
All Usage Examples Of lithium\data\source\MongoDb::connect