Spot\Config::addConnection PHP Method

addConnection() public method

Add database connection
public addConnection ( string $name, string $dsn, array $options = [], $default = false ) : Spot_Adapter_Interface
$name string Unique name for the connection
$dsn string DSN string for this connection
$options array Array of key => value options for adapter
return Spot_Adapter_Interface Spot adapter instance
    public function addConnection($name, $dsn, array $options = array(), $default = false)
    {
        // Connection name must be unique
        if (isset($this->_connections[$name])) {
            throw new Exception("Connection for '" . $name . "' already exists. Connection name must be unique.");
        }
        $dsnp = \Spot\Adapter\AdapterAbstract::parseDSN($dsn);
        $adapterClass = "\\Spot\\Adapter\\" . ucfirst($dsnp['adapter']);
        $adapter = new $adapterClass($dsn, $options);
        // Set as default connection?
        if (true === $default || null === $this->_defaultConnection) {
            $this->_defaultConnection = $name;
        }
        // Store connection and return adapter instance
        $this->_connections[$name] = $adapter;
        return $adapter;
    }

Usage Example

Example #1
0
 public function register()
 {
     $di = $this->getContainer();
     $connections = $di->get('config')['connections'];
     $first = true;
     foreach ($connections as $connection) {
         $di->add('spot.config.' . $connection['name'], function ($logger) use($connection) {
             $cfg = new Config();
             $param = isset($connection['dsn']) ? $connection['dsn'] : $connection;
             $conn = $cfg->addConnection($connection['name'], $param);
             $sqlLogger = new \Laasti\SpotProvider\MonologSqlLogger($logger);
             $conn->getConfiguration()->setSQLLogger($sqlLogger);
             return $cfg;
         }, true)->withArgument('Psr\\Log\\LoggerInterface');
         $di->add('spot.locator.' . $connection['name'], function () use($di, $connection) {
             $spot = new Locator($di->get('spot.config.' . $connection['name']));
             return $spot;
         }, true);
         if ($first) {
             $di->add('Spot\\Config', function () use($di, $connection) {
                 return $di->get('spot.config.' . $connection['name']);
             }, true);
             $di->add('Spot\\Locator', function ($config = null) use($di, $connection) {
                 return $di->get('spot.locator.' . $connection['name'], [$config]);
             }, true);
             $first = false;
         }
     }
 }
All Usage Examples Of Spot\Config::addConnection