根据连接配置构造连接实例

@param array|Closure $connConfig 连接配置/回调函数
@return ConnectionInterface
516032
private function buildConnection($connConfig) {
        //基于数组的连接配置
        if (is_array($connConfig)) {
            $pdoProviderClass = $connConfig['pdoProvider'];
            unset($connConfig['pdoProvider']);

            /* @var $conn PDOProviderInterface */
            $pdoProvider = new $pdoProviderClass($connConfig);

            $conn = new Connection($pdoProvider, $this->logger);
            $conn->setTablePrefix($connConfig['tablePrefix']);
        }
        //回调函数
        //回调函数可以接收当前 ConnectionManager 实例作为参数，当然，这个参数是可选的
        elseif ($connConfig instanceof Closure) {
            $callback = $connConfig;
            $refFunc = new ReflectionFunction($callback);
            $conn = $refFunc->getNumberOfParameters() == 1 ? $callback($this) : $callback();
        } else {
            throw new SqlException('连接配置类型错误');
        }

        return $conn;
    }
1170791
private function getConnectionType(array $config)
    {
        $isGrpcExtensionLoaded = $this->isGrpcLoaded();
        $defaultTransport = $isGrpcExtensionLoaded ? 'grpc' : 'rest';
        $transport = isset($config['transport'])
            ? strtolower($config['transport'])
            : $defaultTransport;

        if ($transport === 'grpc') {
            if (!$isGrpcExtensionLoaded) {
                throw new GoogleException(
                    'gRPC support has been requested but required dependencies ' .
                    'have not been found. ' . $this->getGrpcInstallationMessage()
                );
            }
        }

        return $transport;
    }
876534
public function setHandler(array $config)
    {
        $connect = $config['connect'] ?? [];

        switch (strtolower($config['handler'])) {
            case 'redis':
                $class = Handler\Redis::class;
                $conn = Redis::client($connect);
                break;

            case 'simple':
            case 'simplecache':
                $class = Handler\SimpleCache::class;
                $conn = Cache::simple($connect);
                break;

            case 'cache':
                $class = Handler\Cache::class;
                $conn = Cache::pool($connect);
                break;

            case 'db':
                $class = Handler\Database::class;
                $conn = Database::pdo($connect);
                break;

            default:
                return;
        }

        $settings = $config['settings'] ?? [];
        if (!isset($settings['lifetime']) && isset($this->cookieParams['lifetime'])) {
            $settings['lifetime'] = $this->cookieParams['lifetime'];
        }

        $this->handler = new $class($conn, $settings);
    }
968242
protected function _connect($config)
    {
        # Connect Configuration
        $host     = $config['host'];
        $port     = $config['port'];
        $timeout  = $config['timeout'];
        $user     = $config['user'];
        $password = $config['password'];
        $ssl      = $config['sslConnect'];
 
        $this->connect = $ssl === false
                       ? ftp_connect($host, $port, $timeout)
                       : ftp_ssl_connect($host, $port, $timeout);

        if( empty($this->connect) )
        {
            throw new IOException('Error', 'emptyVariable', 'Connect');
        }

        $this->login = ftp_login($this->connect, $user, $password);

        if( empty($this->login) )
        {
            throw new IOException('Error', 'emptyVariable', 'Login');
        }
    }
181017
public function connect(array $config = [], $linkNum = 0, $autoConnection = false)
    {
        if (isset($this->links[$linkNum])) {
            return $this->links[$linkNum];
        }

        if (!$config) {
            $config = $this->config;
        } else {
            $config = array_merge($this->config, $config);
        }

        // 连接参数
        if (isset($config['params']) && is_array($config['params'])) {
            $params = $config['params'] + $this->params;
        } else {
            $params = $this->params;
        }

        // 记录当前字段属性大小写设置
        $this->attrCase = $params[PDO::ATTR_CASE];

        try {
            if (empty($config['dsn'])) {
                $config['dsn'] = $this->parseDsn($config);
            }

            if ($config['debug']) {
                $startTime = microtime(true);
            }

            $this->links[$linkNum] = new PDO($config['dsn'], $config['username'], $config['password'], $params);

            if ($config['debug']) {
                // 记录数据库连接信息
                $this->log('[ DB ] CONNECT:[ UseTime:' . number_format(microtime(true) - $startTime, 6) . 's ] ' . $config['dsn']);
            }

            return $this->links[$linkNum];
        } catch (\PDOException $e) {
            if ($autoConnection) {
                $this->log('[ ERR ] ' . $e->getMessage());
                return $this->connect($autoConnection, $linkNum);
            } else {
                throw $e;
            }
        }
    }
1291547
public function connect(array $config)
    {
        $options = $this->getOptions($config);

        return $this->createConnection($this->getDsn($config), $config, $options);
    }
544028
public function connect($config = array())
    {
        // TODO: Implement connect() method.
        if (isset($config['database']['cache'])) {
            $configCache = $config['database']['cache'];
            $this->conn = new \Memcache();
            if ($this->conn->connect($configCache['host'], $configCache['port'], $configCache['timeout'])) {
                $this->connected = true;
                return true;
            }
        }
        return false;
    }
1130639
public function connect(array $config): Queue
    {
        if (false === array_key_exists('factory_class', $config)) {
            throw new \LogicException('The factory_class option is missing though it is required.');
        }

        $factoryClass = $config['factory_class'];
        if (false === class_exists($factoryClass) || false === (new \ReflectionClass($factoryClass))->implementsInterface(InteropAmqpConnectionFactory::class)) {
            throw new \LogicException(sprintf('The factory_class option has to be valid class that implements "%s"', InteropAmqpConnectionFactory::class));
        }

        /** @var AmqpConnectionFactory $factory */
        $factory = new $factoryClass([
            'dsn'            => $config['dsn'],
            'host'           => $config['host'],
            'port'           => $config['port'],
            'user'           => $config['login'],
            'pass'           => $config['password'],
            'vhost'          => $config['vhost'],
            'ssl_on'         => $config['ssl_params']['ssl_on'],
            'ssl_verify'     => $config['ssl_params']['verify_peer'],
            'ssl_cacert'     => $config['ssl_params']['cafile'],
            'ssl_cert'       => $config['ssl_params']['local_cert'],
            'ssl_key'        => $config['ssl_params']['local_key'],
            'ssl_passphrase' => $config['ssl_params']['passphrase'],
        ]);

        if ($factory instanceof DelayStrategyAware) {
            $factory->setDelayStrategy(new RabbitMqDlxDelayStrategy());
        }

        /** @var AmqpContext $context */
        $context = $factory->createContext();

        /** @var Dispatcher $dispatcher */
        $dispatcher = app(Dispatcher::class);
        $dispatcher->listen(WorkerStopping::class, function () use ($context) {
            $context->close();
        });

        return new RabbitMQQueue($context, $config);
    }
229096
public function setConfig(array $config = [])
    {
        // 设置App Key
        $this->appKey = isset($config['appKey']) ? $config['appKey'] : '';

        // 设置App Secret
        $this->appSecret = isset($config['appSecret']) ? $config['appSecret'] : '';

        // 沙箱环境
        $this->sandbox = isset($config['sandbox']) ? (bool)$config['sandbox'] : false;

        // 使用HTTPS
        $this->secure = isset($config['secure']) ? (bool)$config['secure'] : false;

        return $this;
    }
367643
protected function getConnection(Configuration $config)
    {
        $connection = $this->getOption('connection');

        switch (true) {
            case is_array($connection):
                $connection = new Connection(
                    array_key_exists('server', $connection) ? $connection['server'] : null,
                    array_key_exists('options', $connection) ? $connection['options'] : [],
                    $config,
                    $this->getEventManager()
                );
                break;

            case $connection instanceof Connection:
                if ($connection->getEventManager() !== $this->getEventManager()) {
                    throw new \RuntimeException(
                        'Cannot use different EventManager instances for DocumentManager and Connection.'
                    );
                }
                break;

            default:
                throw new \InvalidArgumentException('Invalid argument: ' . $connection);
        }

        return $connection;
    }
1234267
protected function getConnections(array $config)
    {
        if (!isset($config['connections'])) {
            throw new \RuntimeException('Configuration must contain a "connections" key');
        }

        if (!is_array($config['connections']) || !$config['connections']) {
            throw new \RuntimeException('Configuration "connections" key must reference a non-empty array');
        }

        $connections = array_filter(
            $config['connections'],
            function ($connection) {
                return $connection instanceof ConnectionInterface;
            }
        );
        if (count($connections) != count($config['connections'])) {
            throw new \RuntimeException(
                'All configuration "connections" array values must implement \Phergie\Irc\ConnectionInterface'
            );
        }

        return $connections;
    }
1238335
public function getConnection($connKey)
    {
        if (isset(self::$connectionObject[$connKey]) && self::$connectionObject[$connKey] instanceof PDO) {
            return self::$connectionObject[$connKey];
        }

        $config = [];
        $config = Configure::getDatabaseConfiguration();

        foreach ($config as $key => $value) {
            if (trim($value['database']) == trim($connKey)) {
                return self::$connectionObject[$connKey] = $this->setConnection($value);
            }
        }
    }
1270890
protected function createConnection($databaseConfig, &$error)
    {
        $error = null;
        try {
            switch ($databaseConfig['type']) {
                case 'MySQLDatabase':
                    $conn = mysqli_init();

                    // Set SSL parameters if they exist. All parameters are required.
                    if (array_key_exists('ssl_key', $databaseConfig) &&
                        array_key_exists('ssl_cert', $databaseConfig) &&
                        array_key_exists('ssl_ca', $databaseConfig)
                    ) {
                        $conn->ssl_set(
                            $databaseConfig['ssl_key'],
                            $databaseConfig['ssl_cert'],
                            $databaseConfig['ssl_ca'],
                            dirname($databaseConfig['ssl_ca']),
                            array_key_exists('ssl_cipher', $databaseConfig)
                                ? $databaseConfig['ssl_cipher']
                                : Config::inst()->get(MySQLiConnector::class, 'ssl_cipher_default')
                        );
                    }
                    @$conn->real_connect(
                        $databaseConfig['server'],
                        $databaseConfig['username'],
                        $databaseConfig['password']
                    );

                    if ($conn && empty($conn->connect_errno)) {
                        $conn->query("SET sql_mode = 'ANSI'");
                        return $conn;
                    } else {
                        $error = ($conn->connect_errno)
                            ? $conn->connect_error
                            : 'Unknown connection error';
                        return null;
                    }
                case 'MySQLPDODatabase':
                    // May throw a PDOException if fails

                    // Set SSL parameters
                    $ssl = null;

                    if (array_key_exists('ssl_key', $databaseConfig) &&
                        array_key_exists('ssl_cert', $databaseConfig)
                    ) {
                        $ssl = array(
                            PDO::MYSQL_ATTR_SSL_KEY => $databaseConfig['ssl_key'],
                            PDO::MYSQL_ATTR_SSL_CERT => $databaseConfig['ssl_cert'],
                        );
                        if (array_key_exists('ssl_ca', $databaseConfig)) {
                            $ssl[PDO::MYSQL_ATTR_SSL_CA] = $databaseConfig['ssl_ca'];
                        }
                        // use default cipher if not provided
                        $ssl[PDO::MYSQL_ATTR_SSL_CA] = array_key_exists('ssl_ca', $databaseConfig)
                            ? $databaseConfig['ssl_ca']
                            : Config::inst()->get(PDOConnector::class, 'ssl_cipher_default');
                    }

                    $conn = @new PDO(
                        'mysql:host=' . $databaseConfig['server'],
                        $databaseConfig['username'],
                        $databaseConfig['password'],
                        $ssl
                    );
                    if ($conn) {
                        $conn->query("SET sql_mode = 'ANSI'");
                        return $conn;
                    } else {
                        $error = 'Unknown connection error';
                        return null;
                    }
                default:
                    $error = 'Invalid connection type: ' . $databaseConfig['type'];
                    return null;
            }
        } catch (Exception $ex) {
            $error = $ex->getMessage();
            return null;
        }
    }
1234771
public function doConnect($config)
    {
        $connectionString = 'sqlite:' . $config['database'];
        return $this->container->build(
            '\PDO',
            array($connectionString, null, null, $config['options'])
        );
    }
412620
final protected function open_db_connection(array $config){

        $dns = 'mysql:host=' . $config['host'] . ';dbname=' . $config['database_name'];

        $this->database_connection = new \PDO($dns, $config['username'], $config['password']
        );

        $this->database_connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

        $this->database_connection->setAttribute(\PDO::ATTR_EMULATE_PREPARES, false);

        return $this->database_connection;
    }
78976
public function addConnection(array $config, $name = 'default')
    {
        $this->connectionResolver->addConnection(
            $this->make($config),
            $name
        );

        return $this;
    }
546741
public function connect(array $config)
	{
		$sqsConfig = array_only($config, array('key', 'secret', 'region', 'default_cache_config'));

		$sqs = SqsClient::factory($sqsConfig);

		return new SqsQueue($sqs, $config['queue']);
	}