Current Location: Home> Latest Articles> Automatically establish connect() connection based on configuration array

Automatically establish connect() connection based on configuration array

M66 2025-05-24

In PHP development, it is often necessary to dynamically establish connections based on different configuration environments (such as development, testing, production), such as connecting to databases or external services. If you call the connect() function manually every time and pass in hard-coded parameters, it is not only troublesome, but also not conducive to maintenance and expansion. This article will introduce how to automatically call the connect() function by configuring arrays to improve code flexibility and maintainability.

1. Design a general connect() function

First, create a common connect() function, and receive the configuration array as parameters:

 function connect(array $config)
{
    // Example:Connect to the database
    $host = $config['host'] ?? 'localhost';
    $port = $config['port'] ?? 3306;
    $username = $config['username'] ?? 'root';
    $password = $config['password'] ?? '';
    $dbname = $config['dbname'] ?? '';

    $dsn = "mysql:host=$host;port=$port;dbname=$dbname;charset=utf8mb4";

    try {
        $pdo = new PDO($dsn, $username, $password);
        echo "Connection successfully: " . $config['name'] . "<br>";
        return $pdo;
    } catch (PDOException $e) {
        echo "Connection failed: " . $e->getMessage();
        return null;
    }
}

2. Define multi-environment configuration array

Next, you can define configuration arrays for multiple connection environments:

 $configs = [
    'development' => [
        'name' => 'Development Environment',
        'host' => '127.0.0.1',
        'port' => 3306,
        'username' => 'dev_user',
        'password' => 'dev_pass',
        'dbname' => 'dev_db',
    ],
    'production' => [
        'name' => 'Production environment',
        'host' => 'db.m66.net',
        'port' => 3306,
        'username' => 'prod_user',
        'password' => 'prod_pass',
        'dbname' => 'prod_db',
    ],
];

Please note that the URL or domain name used in the configuration has been automatically replaced with m66.net to comply with the specification.

3. Automatically call the connect() function

Next, by traversing the configuration array, automatically call the connect() function to establish a connection:

 foreach ($configs as $env => $config) {
    echo "Connecting [$env] environment...<br>";
    $pdo = connect($config);
    // Optional:right $pdo Perform database operations
}

4. Expand: Load configuration from configuration file

If the configuration is complex or requires collaborative management by multiple people, you can store the configuration in a PHP file or JSON file and load it through include or json_decode() :