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

connect() public method

Will set general options on the connection as provided (persistence, encoding).
See also: lithium\data\source\Database::encoding()
public connect ( ) : boolean
return boolean Returns `true` if a database connection could be established, otherwise `false`.
    public function connect()
    {
        $this->_isConnected = false;
        $config = $this->_config;
        if (!$config['database']) {
            throw new ConfigException('No Database configured');
        }
        if (!$config['dsn']) {
            throw new ConfigException('No DSN setup for DB Connection');
        }
        $dsn = $config['dsn'];
        $options = $config['options'] + array(PDO::ATTR_PERSISTENT => $config['persistent'], PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION);
        try {
            $this->connection = new PDO($dsn, $config['login'], $config['password'], $options);
        } catch (PDOException $e) {
            preg_match('/SQLSTATE\\[(.+?)\\]/', $e->getMessage(), $code);
            $code = $code[1] ?: 0;
            switch (true) {
                case $code === 'HY000' || substr($code, 0, 2) === '08':
                    $msg = "Unable to connect to host `{$config['host']}`.";
                    throw new NetworkException($msg, null, $e);
                    break;
                case in_array($code, array('28000', '42000')):
                    $msg = "Host connected, but could not access database `{$config['database']}`.";
                    throw new ConfigException($msg, null, $e);
                    break;
            }
            throw new ConfigException("An unknown configuration error has occured.", null, $e);
        }
        $this->_isConnected = true;
        if ($this->_config['encoding']) {
            $this->encoding($this->_config['encoding']);
        }
        return $this->_isConnected;
    }

Usage Example

Example #1
0
 /**
  * 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 lithium\data\source\dataase\adapter\PostgreSql::timezone()
  * @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;
 }
All Usage Examples Of lithium\data\source\Database::connect