Multiple Instances

Connect to more than one database at the same time.

When you need this

Sometimes a single database connection is not enough. Typical scenarios:

  • Your application reads from a replica and writes to a primary database
  • You run a multi-tenant system where each tenant has its own database
  • You need to synchronize data between two separate databases
  • You have a separate analytics or logging database

Creating a named instance

Pass an instance key to the constructor to create a named, independent connection. Each instance has its own connection, prefix, and query state.

// Default instance (instance = 'default')
$db = new PDOdb([
    'host'     => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'db'       => 'main_db',
]);

// Second instance with its own connection
$dbReadonly = new PDOdb([
    'host'     => 'replica.example.com',
    'username' => 'readonly_user',
    'password' => 'secret',
    'db'       => 'main_db',
    'instance' => 'readonly',
]);
Each instance is completely isolated – transactions, locks, prefix and query state are all separate. What happens on one instance has no effect on another.

Retrieve a named instance anywhere

Once created, you can retrieve a named instance from anywhere in your code using the static getInstance() method:

// Retrieve the default instance
$db = PDOdb::getInstance();

// Retrieve the named instance
$dbReadonly = PDOdb::getInstance('readonly');

// Step by step
$dbReadonly->whereInt('active', 1);
$users = $dbReadonly->get('users');

// Fluent
$users = PDOdb::getInstance('readonly')
              ->whereInt('active', 1)
              ->get('users');

// → SELECT * FROM users WHERE active = 1

Practical example – multi-tenant

Each tenant gets its own connection with a separate database and prefix:

// Tenant A
$dbA = new PDOdb([
    'host'     => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'db'       => 'tenant_a',
    'prefix'   => 'a_',
    'instance' => 'tenant_a',
]);

// Tenant B
$dbB = new PDOdb([
    'host'     => 'localhost',
    'username' => 'user',
    'password' => 'secret',
    'db'       => 'tenant_b',
    'prefix'   => 'b_',
    'instance' => 'tenant_b',
]);

// Both run independently
$dbA->whereInt('active', 1);
$usersA = $dbA->get('users');
// → SELECT * FROM a_users WHERE active = 1

$dbB->whereInt('active', 1);
$usersB = $dbB->get('users');
// → SELECT * FROM b_users WHERE active = 1

Closing connections

To close a specific connection when you no longer need it:

// Close one connection
$db->disconnect('readonly');

// Close all connections
$db->disconnectAll();
Closing a connection does not remove its configuration. The next query on that instance will automatically reconnect.

See also