Welcome Guest, Not a member yet? Register   Sign In
Codeigniter 4 - How to connect to two or multiple databases
#1

(This post was last modified: 01-28-2024, 03:16 AM by Corsari.)

Hello
searching on the forum I have found only two really old topics (2007 and 2008) about how to connect to two or more databases
the manual is also a bit cryptic
https://codeigniter.com/user_guide/datab...-databases
because it doesn't detail about if just and only the .env file has to be edited or just and only the app/Config/Database.php has to be edited
... or if they should be edited BOTH accordingly
(well it really tells nothing, since the manual here looks conceived for gurus Shy )

I suppose that thing with current Codeigniter 4 could be slightly changed

so, accordingly to this forum section title Smile , thank you in advance for sharing the best practice for configuring the connection to two databases in Codeigniter 4
Reply
#2

(This post was last modified: 01-28-2024, 07:55 AM by davis.lasis.)

https://codeigniter.com/user_guide/datab...ation.html

1. make new DB config in App/Config/Database.php

PHP Code:
<?php

namespace Config;

use 
CodeIgniter\Database\Config;

class 
Database extends Config
{
    // ...

    public array $second_db = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'second_database_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => true,
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'    => 3306,
    ];



2. You can control sensitive info through env or .env file in root folder
PHP Code:
database.second_db.hostname localhost
database
.second_db.username root
database
.second_db.password =
database.second_db.database second_database_name
database
.second_db.DBDriver MySQLi
database
.second_db.DBDebug false
database
.second_db.DBPrefix =
database.second_db.port 3306 


3. you can connect to this DB in any Controller or other instance

PHP Code:
class AdminController extends AdminBaseController
{
    /**
    * @param RequestInterface $request
    * @param ResponseInterface $response
    * @param LoggerInterface $logger
    *
    * @throws Exception
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        parent::initController($request$response$logger);

        $second_db db_connect('second_db');
    }


4. if you don't need to connect to it, just use it, then add DB group directly in model and that model will work with your seleteced database instance

PHP Code:
class AnotherModel extends Model
{
    protected $table 'db_table';
    protected $primaryKey 'id';
    protected $DBGroup 'second_db';

5. if you need to create a new instance of DB "on a flow" and therefore you can't use hardcoded config, then you have an option to provide DB config array and that will create a new isntance
PHP Code:
class AdminController extends AdminBaseController
{
    /**
    * @param RequestInterface $request
    * @param ResponseInterface $response
    * @param LoggerInterface $logger
    *
    * @throws Exception
    */
    public function initController(RequestInterface $requestResponseInterface $responseLoggerInterface $logger)
    {
        parent::initController($request$response$logger);

        $another_db_config = [
            'DSN'      => '',
            'hostname' => 'localhost',
            'username' => 'root',
            'password' => '',
            'database' => 'another_database_name',
            'DBDriver' => 'MySQLi',
            'DBPrefix' => '',
            'pConnect' => false,
            'DBDebug'  => true,
            'charset'  => 'utf8',
            'DBCollat' => 'utf8_general_ci',
            'swapPre'  => '',
            'encrypt'  => false,
            'compress' => false,
            'strictOn' => false,
            'failover' => [],
            'port'    => 3306,
        ];


        $another_db db_connect($another_db_config);

        OR

        $another_db Database::connect($another_db_config);

    }


I am using all those cases in my projects. Works perfect, but...

Wouldn't that be great to change Database config a bit?

Instead of using $default as array, but make it more dynamic?

For example
1. remove $default

PHP Code:
public array $default = [
    ...
]; 


2. add array $databases (or better name it array $instances)

PHP Code:
public array $instances = [
    'default' => [ $default array ],
    'second' => [ $my_db array ],
    'another' => [...],
]; 

Therefore we could create list as long as we need and most important this config list could be populated with registrars from default DB or so...

Not sure how many of System core files should be changed to achieve this, but at least would like to hear your thoughts on this.

p.s. this change to $instances multi-array would help my projects as lot, because i am building company's HUB who could connect / control ~50 children projects and websites.
Would be crazy to manually manage through config or env
Reply
#3

(01-28-2024, 07:37 AM)davis.lasis Wrote: 2. add array $databases (or better name it array $instances)

PHP Code:
public array $instances = [
    'default' => [ $default array ],
    'second' => [ $my_db array ],
    'another' => [...],
]; 

Therefore we could create list as long as we need and most important this config list could be populated with registrars from default DB or so...

Probably the change does not help.

Because the Database config instance is required before creating a DB connection object.
So if you try to connect to the default DB in the constructor (by registrars) in the Database config class,
there is no DB connection yet.

After all, the Database config values must be all static values.

If you want to get database config from the default DB, you need to do something after instantiated the default DB connection.

You can add properties dynamically if you set #[\AllowDynamicProperties]:
https://www.php.net/manual/en/class.allo...erties.php
Reply
#4

Thank you both for the guidelines and hints
Hopefully this topic can be of support for others newbie too
Reply




Theme © iAndrew 2016 - Forum software by © MyBB