Files
youlegames/codes/agent/game-docker/env_config.php
2026-04-10 16:44:13 +08:00

66 lines
2.2 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* 统一环境变量加载器
*
* 优先读取环境变量Docker 注入),不存在时使用默认值。
* 所有 PHP 服务api、dlweb共用此文件通过 require_once 引入。
*
* 用法:
* require_once __DIR__ . '/env_config.php';
* $host = env('API_DB_HOST', '127.0.0.1');
*/
if (!function_exists('env')) {
/**
* 获取环境变量值,不存在时返回默认值
* @param string $key 环境变量名
* @param mixed $default 默认值
* @return mixed
*/
function env($key, $default = null) {
$value = getenv($key);
if ($value === false) {
return $default;
}
// 自动类型转换
switch (strtolower($value)) {
case 'true': return true;
case 'false': return false;
case 'null': return null;
}
return $value;
}
}
// ============================================
// 如果存在 .env 文件,手动解析(非 Docker 时的本地开发支持)
// Docker 环境下不需要 .env 文件,由 docker-compose 注入
// ============================================
if (!function_exists('_load_env_file')) {
function _load_env_file() {
// 搜索 .env 文件位置:当前目录 -> 上级 -> game-docker 根目录
$search_paths = [
__DIR__ . '/.env',
dirname(__DIR__) . '/.env',
dirname(dirname(__DIR__)) . '/.env',
];
foreach ($search_paths as $path) {
if (file_exists($path)) {
$lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
$line = trim($line);
if ($line === '' || $line[0] === '#') continue;
if (strpos($line, '=') === false) continue;
list($name, $value) = array_map('trim', explode('=', $line, 2));
// 只在环境变量未设置时才加载
if (getenv($name) === false) {
putenv("$name=$value");
}
}
return;
}
}
}
_load_env_file();
}