lithium\data\source\database\adapter\PostgreSql::connect PHP Method

connect() public method

Connects to the database by constructing DSN string and creating a PDO intance using the parent class. Will set specific options on the connection as provided (timezone, schema).
See also: lithium\data\source\database\adapter\PostgreSql::timezone()
public connect ( ) : boolean
return boolean Returns `true` if a database connection could be established, otherwise `false`.
    public function connect()
    {
        if (!$this->_config['dsn']) {
            $host = $this->_config['host'];
            list($host, $port) = explode(':', $host) + array(1 => "5432");
            $dsn = "pgsql:host=%s;port=%s;dbname=%s";
            $this->_config['dsn'] = sprintf($dsn, $host, $port, $this->_config['database']);
        }
        if (!parent::connect()) {
            return false;
        }
        if ($this->_config['schema']) {
            $this->searchPath($this->_config['schema']);
        }
        if ($this->_config['timezone']) {
            $this->timezone($this->_config['timezone']);
        }
        return true;
    }

Usage Example

 /**
  * Tests that this adapter can connect to the database, and that the status is properly
  * persisted.
  */
 public function testDatabaseConnection()
 {
     $db = new PostgreSql(array('autoConnect' => false) + $this->_dbConfig);
     $this->assertTrue($db->connect());
     $this->assertTrue($db->isConnected());
     $this->assertTrue($db->disconnect());
     $this->assertFalse($db->isConnected());
     $db = new PostgreSql(array('autoConnect' => false, 'encoding' => null, 'persistent' => false, 'host' => 'localhost:5432', 'login' => 'garbage', 'password' => '', 'database' => 'garbage', 'init' => true, 'schema' => 'garbage') + $this->_dbConfig);
     $this->expectException();
     $this->assertFalse($db->connect());
     $this->assertFalse($db->isConnected());
     $this->assertTrue($db->disconnect());
     $this->assertFalse($db->isConnected());
 }