Autarky\Database\ConnectionFactory::makePdo PHP Method

makePdo() public method

Create a new PDO instance.
public makePdo ( array $config, string $connection = null ) : PDO
$config array
$connection string Name of the connection - used for exception messages
return PDO
    public function makePdo(array $config, $connection = null)
    {
        if (!isset($config['driver']) && !isset($config['dsn'])) {
            throw new InvalidArgumentException('DSN or driver must be set');
        }
        $options = isset($config['pdo_options']) ? $config['pdo_options'] : [];
        unset($config['pdo_options']);
        $options = array_replace($this->defaultPdoOptions, $options);
        $initCommands = isset($config['pdo_init_commands']) ? $config['pdo_init_commands'] : [];
        unset($config['pdo_init_commands']);
        // SQLite needs special treatment
        if (isset($config['driver']) && $config['driver'] == 'sqlite') {
            $this->validate($config, 'path', $connection);
            $dsn = $this->makeSqliteDsn($config['path']);
            return $this->makePdoInner($dsn, null, null, $options, $initCommands);
        } elseif (isset($config['dsn']) && strpos($config['dsn'], 'sqlite:') === 0) {
            return $this->makePdoInner($config['dsn'], null, null, $options, $initCommands);
        }
        $this->validate($config, 'username', $connection, false);
        $username = $config['username'];
        unset($config['username']);
        $this->validate($config, 'password', $connection, true);
        $password = $config['password'];
        unset($config['password']);
        if (isset($config['dsn'])) {
            $dsn = $config['dsn'];
        } else {
            $driver = $config['driver'];
            unset($config['driver']);
            $this->validate($config, 'host', $connection);
            $this->validate($config, 'dbname', $connection);
            $dsn = $this->makeDsn($driver, $config);
        }
        return $this->makePdoInner($dsn, $username, $password, $options, $initCommands);
    }

Usage Example

Example #1
0
 /**
  * Get a PDO instance.
  *
  * @param  string|null $connection Null fetches the default connection.
  *
  * @return \PDO
  */
 public function getPdo($connection = null)
 {
     if ($connection === null) {
         $connection = $this->defaultConnection;
     }
     if (isset($this->instances[$connection])) {
         return $this->instances[$connection];
     }
     $config = $this->getConnectionConfig($connection);
     return $this->instances[$connection] = $this->factory->makePdo($config, $connection);
 }