Current Location: Home> Latest Articles> How to call connect() dynamically in a multi-database configuration file

How to call connect() dynamically in a multi-database configuration file

M66 2025-05-31

In daily development, especially in large applications or microservice architectures, we often face the situation of dealing with multiple databases. These databases may belong to different business modules, or be deployed on different servers. In order to manage these database connections more flexibly, we can dynamically call the connect function through the configuration file to implement database connection management. This article will explain in detail how to implement this feature in PHP.

1. Structural design of multi-database configuration files

First, we need to design a well-structured configuration file to store connection information of different databases. It is recommended to use PHP array or JSON format for easy reading and management. Here is an example using PHP arrays as configuration:

 // db_config.php
return [
    'main_db' => [
        'host' => '127.0.0.1',
        'dbname' => 'main_database',
        'user' => 'root',
        'password' => 'password',
    ],
    'analytics_db' => [
        'host' => '192.168.1.100',
        'dbname' => 'analytics',
        'user' => 'analytics_user',
        'password' => 'secure_pass',
    ],
];

2. Encapsulate database connection function

In order to improve code reusability and maintainability, we can encapsulate a common database connection function and dynamically connect different databases by passing parameters.

 // db_connect.php
function connect($dbKey) {
    $config = include 'db_config.php';
    
    if (!isset($config[$dbKey])) {
        throw new Exception("Database configuration for '{$dbKey}' not found.");
    }

    $db = $config[$dbKey];

    $dsn = "mysql:host={$db['host']};dbname={$db['dbname']};charset=utf8mb4";

    try {
        $pdo = new PDO($dsn, $db['user'], $db['password'], [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        ]);
        return $pdo;
    } catch (PDOException $e) {
        error_log("Database connection error: " . $e->getMessage());
        throw new Exception("Could not connect to the database.");
    }
}

3. Dynamic call examples

In business logic, we only need to pass in the corresponding database configuration keys to easily obtain the connection.

 require 'db_connect.php';

try {
    $mainDb = connect('main_db');
    $analyticsDb = connect('analytics_db');

    // use $mainDb or $analyticsDb Perform database operations
    $stmt = $analyticsDb->query('SELECT COUNT(*) as total FROM page_views');
    $result = $stmt->fetch();

    echo "Total page visits:" . $result['total'];

} catch (Exception $e) {
    echo "mistake:" . $e->getMessage();
}

4. Advanced suggestions

  1. Cache connection instances : You can consider using static variables or singleton mode to cache PDO objects to avoid repeated connections to the same database.

  2. Configuring encryption and security : The database configuration file should be fully controlled with permissions, and sensitive information can be stored using encryption if necessary.

  3. Logging and error handling : Be sure to record the error log of connection failure for later tracking and maintenance.

  4. Configuration Center Integration : In the microservice architecture, database configurations can be centrally managed, such as unified management and hot updates through services such as https://m66.net/config-center .

5. Summary

By using configuration files and dynamically calling the connect function, we can achieve flexible and unified multi-database connection management. Such a design not only makes the system structure clearer, but also lays a good foundation for future expansion. In actual projects, selecting the appropriate structure and implementation method based on project needs is the key to improving development efficiency and system stability.