Many DB connections

How do you create multiple DB connections using the Singleton pattern? Or maybe it’s better to come up with to share the same class, but multiple connections?

+3
source share
5 answers

How to use Factory pattern to return the same instance for each connection, e.g.

ConnectionFactory::getInstance(ConnectionFactory::DEVELOPMENT);

Gets an instance Connectionto connect to the development database.

Connection ConnectionFactory, . , , Connection.

+3

Singleton, ? Singleton -, , , , . , Singleton PHP .

0

, , , , - :

interface Connection_Interface
{
    public function connect();
    public function disconnect();
    public function exec($sql);
    // etc...
}

class Connection implements Connection_Interface
{
    public function __construct($host, $username, $password, $database);
    public function connect();
    public function disconnect();
    public function exec($sql);
    // etc...
}

, :

class Connection_Multiple implements Connection_Interface
{
    protected $_connections = array();        

    public function __construct();
    public function add(Connection $connection);
    public function connect();
    public function disconnect();
    public function exec($sql)
    {
        // decide here which connection you want to use, then...
        return $connection->exec($sql);
    }
    // etc...
}

Since both a single connection and several connection classes implement the same interface, you can use either the exact same way.

0
source

I came up with this solution:

class Database {
    private static $instances = array();

    public static function getInstance($connection='default') {
        if (!array_key_exists($connection,self::$instances)) {
            self::$instances[$connection] = new Database($connection);
        }
        return self::$instances[$connection];
    }

    private function __construct($connection) {
        $this->credentials = // getting credentials from config by $connection...
        $this->connect(); // connect using credentials
    }
}

$DB1 = Database::getInstance('development');
$DB2 = Database::getInstance('production');

It seems to work for me. Is this a Singleton pattern or something mixed?

0
source

Source: https://habr.com/ru/post/1702569/


All Articles