Codeigniter 4 上的自定义 .env 变量

Dea*_*oro 4 environment-variables codeigniter-4

通常,如果我想更改 CI4 项目中的数据库主机名,我将在 .env 文件中更改它并更改

database.default.hostname = localhost

但现在我需要在环境中使用 MYSQL_HOST 来更改主机名,如下所示

MYSQL_HOST = localhost

我可以在 CI4 中这样做吗?如果我将 Database.php 文件更改为,则会出现错误

public $default = [
    'DSN'      => '',
    'hostname' => getenv('MYSQL_HOST'),
    '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,
];
Run Code Online (Sandbox Code Playgroud)

Dea*_*oro 5

我找到了答案,假设你的 .env 文件中有这个

MYSQL_HOST = localhost
MYSQL_USERNAME = root
MYSQL_PASSWORD = root
Run Code Online (Sandbox Code Playgroud)

因此,如果您想更改 CI4 数据库的主机名,您可以添加

$this->default['hostname'] = getenv('MYSQL_HOST');

app/config/Database.php 中的 __construct() 内部

所以它会看起来像这样

public function __construct()
{
    parent::__construct();

    // Ensure that we always set the database group to 'tests' if
    // we are currently running an automated test suite, so that
    // we don't overwrite live data on accident.
    if (ENVIRONMENT === 'testing') {
        $this->defaultGroup = 'tests';
    }
    $this->default['hostname'] = getenv('MYSQL_HOST');
    $this->default['username'] = getenv('MYSQL_USERNAME');
    $this->default['password'] = getenv('MYSQL_PASSWORD');
}
Run Code Online (Sandbox Code Playgroud)

好吧,这仅适用于您想要自定义 .env 并且不想使用默认 CI4 的情况database.default.hostname