增加docke部署
This commit is contained in:
65
codes/agent/game-docker/env_config.php
Normal file
65
codes/agent/game-docker/env_config.php
Normal file
@@ -0,0 +1,65 @@
|
||||
<?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();
|
||||
}
|
||||
Reference in New Issue
Block a user