codeigniter4 / codeigniter4/CodeIgniter4

Add setInstance() support for runtime database switching

Abierto
#9,812 5 comentarios 0 reacciones 0 asignados Ver en GitHub
enhancement
Lenguaje dominante
PHP
Estrellas
6k
Forks
2k
Merge medio
1 d 11 h
PR fusionados (30 d)
73

Descripción

### PHP Version

8.3

### CodeIgniter4 Version

4.6.1

### CodeIgniter4 Installation Method

Composer (using `codeigniter4/appstarter`)

### Which operating systems have you tested for this bug?

Windows

### Which server did you use?

apache

### Database

MySQL

### What happened?

I would like to request a new method in Config\Database that allows developers to set or override a database connection instance at runtime without modifying the framework core.

This is especially useful when a project needs dynamic database switching, such as in:

Multi-tenant SaaS applications

ERP systems with client-specific databases

“Switch DB per request” API requirements

Dynamic “connect with custom credentials” scenarios

Currently, CodeIgniter 4 allows Database::connect($group) but there is no official method to replace or inject a database instance for a given group.

Proposed Method

Add this method in system/Database/Config.php:

public static function setInstance(string $group, array $config)
{
static::ensureFactory();

$connection = static::$factory->load($config, $group);

static::$instances[$group] = $connection;

return $connection;
}

Why this is needed

Today, Database::connect() always loads config from app/Config/Database.php.

To use a custom connection (hostname, username, password, database), we must create a fake group name or override config objects — both are hacky.

Dynamic DB switching is common in modern SaaS, ERP, and enterprise applications.

This addition would provide a clean, supported API for runtime DB instance control.

Example Use Case
$dbConfig = [
'DSN' => '',
'hostname' => $tenantHost,
'username' => $tenantUser,
'password' => $tenantPass,
'database' => $tenantDb,
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
];

$connection = \Config\Database::setInstance('tenant', $dbConfig);

$db = \Config\Database::connect('tenant');

This gives developers the power to switch databases safely and officially.

Backward Compatibility

This method does not change any existing behavior.

It only adds a new optional utility method.

No BC breaks.

Conclusion

This feature will make CodeIgniter 4 significantly more flexible for advanced and enterprise applications that require dynamic DB switching.

Thank you for considering this enhancement! 🙏

### Steps to Reproduce

I would like to request a new method in Config\Database that allows developers to set or override a database connection instance at runtime without modifying the framework core.

This is especially useful when a project needs dynamic database switching, such as in:

Multi-tenant SaaS applications

ERP systems with client-specific databases

“Switch DB per request” API requirements

Dynamic “connect with custom credentials” scenarios

Currently, CodeIgniter 4 allows Database::connect($group) but there is no official method to replace or inject a database instance for a given group.

Proposed Method

Add this method in system/Database/Config.php:

public static function setInstance(string $group, array $config)
{
static::ensureFactory();

$connection = static::$factory->load($config, $group);

static::$instances[$group] = $connection;

return $connection;
}

Why this is needed

Today, Database::connect() always loads config from app/Config/Database.php.

To use a custom connection (hostname, username, password, database), we must create a fake group name or override config objects — both are hacky.

Dynamic DB switching is common in modern SaaS, ERP, and enterprise applications.

This addition would provide a clean, supported API for runtime DB instance control.

Example Use Case
$dbConfig = [
'DSN' => '',
'hostname' => $tenantHost,
'username' => $tenantUser,
'password' => $tenantPass,
'database' => $tenantDb,
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
];

$connection = \Config\Database::setInstance('tenant', $dbConfig);

$db = \Config\Database::connect('tenant');

This gives developers the power to switch databases safely and officially.

Backward Compatibility

This method does not change any existing behavior.

It only adds a new optional utility method.

No BC breaks.

Conclusion

This feature will make CodeIgniter 4 significantly more flexible for advanced and enterprise applications that require dynamic DB switching.

Thank you for considering this enhancement! 🙏

### Expected Output

I would like to request a new method in Config\Database that allows developers to set or override a database connection instance at runtime without modifying the framework core.

This is especially useful when a project needs dynamic database switching, such as in:

Multi-tenant SaaS applications

ERP systems with client-specific databases

“Switch DB per request” API requirements

Dynamic “connect with custom credentials” scenarios

Currently, CodeIgniter 4 allows Database::connect($group) but there is no official method to replace or inject a database instance for a given group.

Proposed Method

Add this method in system/Database/Config.php:

public static function setInstance(string $group, array $config)
{
static::ensureFactory();

$connection = static::$factory->load($config, $group);

static::$instances[$group] = $connection;

return $connection;
}

Why this is needed

Today, Database::connect() always loads config from app/Config/Database.php.

To use a custom connection (hostname, username, password, database), we must create a fake group name or override config objects — both are hacky.

Dynamic DB switching is common in modern SaaS, ERP, and enterprise applications.

This addition would provide a clean, supported API for runtime DB instance control.

Example Use Case
$dbConfig = [
'DSN' => '',
'hostname' => $tenantHost,
'username' => $tenantUser,
'password' => $tenantPass,
'database' => $tenantDb,
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
];

$connection = \Config\Database::setInstance('tenant', $dbConfig);

$db = \Config\Database::connect('tenant');

This gives developers the power to switch databases safely and officially.

Backward Compatibility

This method does not change any existing behavior.

It only adds a new optional utility method.

No BC breaks.

Conclusion

This feature will make CodeIgniter 4 significantly more flexible for advanced and enterprise applications that require dynamic DB switching.

Thank you for considering this enhancement! 🙏

### Anything else?

_No response_

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

Comienza en system/Database/Config.php y lee el flujo existente de Config::connect(), incluidos ensureFactory(), la llamada de carga de la factory y el almacenamiento de instancias. Compara el comportamiento propuesto de setInstance() con ese flujo y determina los casos de aceptación para la configuración personalizada y las llamadas posteriores a connect('tenant').

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
mysql, php
Área
backend-api-design, databases
Tipo de issue
Nueva funcionalidad
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Estancado
Claridad
Bastante claro
Aptitud para principiantes
35/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.