0%

php框架中的.env文件是如何加载的

设置国内源

阿里云镜像设置

1
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

拉取依赖

拉取名字为vlucas/phpdotenv的依赖
添加composer.json文件中的require中添加

1
2
3
4
5
6
7
8
9
10
11
12
13
"require": {
"php": "^7.2",
"ext-json": "*",
"monolog/monolog": "^2.1",
"php-di/php-di": "^6.1",
"predis/predis": "^1.1",
"rmccue/requests": "^1.7",
"slim/psr7": "^1.1",
"slim/slim": "^4.5",
"slim/twig-view": "^3.0",
"twig/twig": "^2.12",
"vlucas/phpdotenv": "^5.0"
},
1
composer update

使用依赖

在项目中新建文件,使用依赖,我在app/下新建一个文件名为env.php的文件,内容为:

1
2
3
4
5
6
7
<?php
try {
$dotenv = Dotenv\Dotenv::createImmutable(dirname(__DIR__));
$dotenv->load();
} catch (\Dotenv\Exception\InvalidPathException $e) {

}

入口加载

新建的文件env.php需在框架的入口文件中加载,否则不会生效
我目前使用的是Slim框架,入口文件在public下的index.php,注意,需要首先加载env.php文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<?php
declare(strict_types=1);

use App\Application\Handlers\HttpErrorHandler;
use App\Application\Handlers\ShutdownHandler;
use App\Application\ResponseEmitter\ResponseEmitter;
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;

require __DIR__ . '/../vendor/autoload.php';

// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();

if (false) { // Should be set to true in production
$containerBuilder->enableCompilation(__DIR__ . '/../var/cache');
}

// load .env 首先加载
require __DIR__ . '/../app/env.php';

// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);

// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);

// Set up repositories
$repositories = require __DIR__ . '/../app/repositories.php';
$repositories($containerBuilder);

测试

这时候尝试在根目录下新建.env文件,设置常量,通过$_ENV[‘’]就能获取到.env中的变量

.env

1
2
3
4
5
6
7
8
# 版本
VERSION = 1.0.0

## db
DB_HOST=192.168.1.252
DB_DATABASE=knight_s
DB_USER=root
DB_PASSWORD=dev2312

获取

1
new PDO(sprintf('mysql:host=%s;dbname=%s',$_ENV['DB_HOST'],$_ENV['DB_DATABASE']),  $_ENV['DB_USER'], $_ENV['DB_PASSWORD'])