如何使用 yii2 基本模板使用 vlucas/phpdotenv 包创建环境变量?

问题描述 投票:0回答:1

我正在使用 yii 2 基本模板。我尝试生成不同的环境。例如:开发、测试、生产。

所以我安装了这个包

"vlucas/phpdotenv": "^5.6"

在根文件夹中,我创建了一个 .env 文件,其内容为:

MYSQL_DSN = pgsql:host=localhost;port=5432;dbname=db
MYSQL_USERNAME = postgres
MYSQL_PASSWORD = pass

在 config/db.php 中我有这个:

<?php
// phpcs:ignoreFile

return [
    'class' => 'yii\db\Connection',
    'dsn' => $_ENV['MYSQL_DSN'],
    'username' => $_ENV['MYSQL_USERNAME'],
    'password' => $_ENV['MYSQL_PASSWORD'],
    'charset' => 'utf8',    
];

我的 web/index.php 看起来:

<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$config = require __DIR__ . '/../config/web.php';

(new yii\web\Application($config))->run();

但是如果我现在做 php yii 服务。我收到此错误:

Warning: Undefined array key "MYSQL_DSN" in C:\repos\internet_backend\config\db.php on line 6
PHP Warning:  Undefined array key "MYSQL_USERNAME" in C:\repos\internet_backend\config\db.php on line 7

问题:但是如何测试呢?

php yii2 yii-extensions yii2-basic-app
1个回答
0
投票

您需要使用

Dotenv\Dotenv
类来加载
.env
文件。您应该在加载 Composer 自动加载器之后、加载配置文件之前在
web/index.php
文件中执行此操作。

<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

require __DIR__ . '/../vendor/autoload.php';
require __DIR__ . '/../vendor/yiisoft/yii2/Yii.php';

$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();

$config = require __DIR__ . '/../config/web.php';

(new yii\web\Application($config))->run();

您可能需要以类似的方式修改项目根目录中的

yii
文件。

此外,

=
文件中的
.env
周围不应有空格。

© www.soinside.com 2019 - 2024. All rights reserved.