'Codeigniter 4 get configuration array by passing a dbgroup

Many websites including official site state about connecting database connections on a dbgroup, however I hardly found a website that talks about getting only an array of configuration.

This idea is that we can make several data adapter objects like OAuth\Pdo without an unused real database connection to get the config.

How can I achieve this?



Solution 1:[1]

Found an answer from looking at the system class CodeIgniter\Config\BaseConfig.

The files in app/Config including app/Config/Database.php are instances of BaseConfig, which means we can get the public properties of Database config by:

$database = new \Config\Database();

Getting configuration array by passing a dbgroup will then remain in three steps:

Duplicate a database connection in .env and update the values:

database.newdbgroup.hostname = localhost
database.newdbgroup.database = newdbgroup
database.newdbgroup.username = newdbgroup-username
database.newdbgroup.password = newdbgroup-password
database.newdbgroup.DBDriver = MySQLi
database.newdbgroup.DBPrefix =

Duplicate a database connection in app/Config/Database.php. We should not update the values this time:

public $newdbgroup = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => '',
    'password' => '',
    'database' => '',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'swapPre'  => '',
    'encrypt'  => false,
    'compress' => false,
    'strictOn' => false,
    'failover' => [],
    'port'     => 3306,
];

Check the expected outcome:

$database = new \Config\Database();

echo '<pre>';
var_dump($database->newdbgroup);
echo '</pre>';

exit();

Which outputs:

array(17) {
  ["DSN"]=>
  string(0) ""
  ["hostname"]=>
  string(9) "localhost"
  ["username"]=>
  string(19) "newdbgroup-username"
  ["password"]=>
  string(19) "newdbgroup-password"
  ["database"]=>
  string(10) "newdbgroup"
  ["DBDriver"]=>
  string(6) "MySQLi"
  ["DBPrefix"]=>
  string(0) ""
  ["pConnect"]=>
  bool(false)
  ["DBDebug"]=>
  bool(false)
  ["charset"]=>
  string(4) "utf8"
  ["DBCollat"]=>
  string(15) "utf8_general_ci"
  ["swapPre"]=>
  string(0) ""
  ["encrypt"]=>
  bool(false)
  ["compress"]=>
  bool(false)
  ["strictOn"]=>
  bool(false)
  ["failover"]=>
  array(0) {
  }
  ["port"]=>
  int(3306)
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mondayrris