You are here

public function ConnectionFactory::get in Dbal connection 8

Gets a DBAL connection to the given target.

Parameters

string $target: Database connection as named in global $databases parameter.

Return value

\Doctrine\DBAL\Connection Requested connection.

File

src/ConnectionFactory.php, line 53

Class

ConnectionFactory
Provides a connection factory for connection to databases via doctrine/dbal.

Namespace

Drupal\dbal

Code

public function get($target = 'default') {
  if (!isset($this->cache[$target])) {
    if (!isset($this->info[$target])) {

      // Fallback to default connection.
      $target = 'default';
    }
    $info = $this->info[$target]['default'];
    $options = [
      'dbname' => $info['database'],
      'user' => $info['username'] ?? '',
      'password' => $info['password'] ?? '',
      'driver' => 'pdo_' . $info['driver'],
    ];
    if (isset($info['host'])) {
      $options['host'] = $info['host'];
    }
    if (isset($info['unix_socket'])) {
      $options['unix_socket'] = $info['unix_socket'];
    }
    if (isset($info['port'])) {
      $options['port'] = $info['port'];
    }
    $this->cache[$target] = DriverManager::getConnection($options, new Configuration());
    if ($info['driver'] == 'sqlite') {
      $this
        ->sqliteDatabases($this->cache[$target], $info['prefix'], $info['database']);
    }
  }
  return $this->cache[$target];
}