brannow/envyml

从env.yml文件中注册环境变量

2.0.1 2023-05-31 06:53 UTC

This package is auto-updated.

Last update: 2024-09-16 14:04:44 UTC


README

symfony/dotenv适配器,用于加载env.yml文件

env文件将与symfony文件缓存适配器一起缓存(每次请求都会检查env.yml的修改时间,更新将立即使缓存失效)

yaml语法将重新格式化以匹配扁平环境结构。嵌套元素键将通过' _ '(下划线)连接。(数字列表是KEY_0,KEY_1)

例如

Vendor:
  SSO:
    Secret: superSecret
    Provider: stuff
  Captcha:
    secret: otherSecret
    Domain: http://oldDomain
    
Vendor_Captcha:
  Domain: https://domain

将产生系统环境变量

Vendor_SSO_Secret = superSecret
Vendor_SSO_Provider = stuff
Vendor_Captcha_Secret = otherSecret
Vendor_Captcha_Domain = https://domain

安装

composer: composer require brannow/envyml

集成后

免责声明:所有显示的代码均基于symfony 5.0(其他symfony版本可能需要更新才能运行)

需要从index.phpbin/console中删除dotenv代码片段

// ...

// env.yml loader announcement, this will disable dotenv loader
$_SERVER['APP_RUNTIME'] = \Brannow\Component\Envyml\SymfonyRuntime::class;

// set the custom APP_RUNTIME before this line!
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

// ...

更新到您的env.yml位置路径

putenv(ENV_FILE_PATH, 'ABSOLUTE_PATH_HERE')

或更改入口脚本(index.php / console)

// env.yml loader announcement, this will disable dotenv loader
$_SERVER['APP_RUNTIME'] = \Brannow\Component\Envyml\SymfonyRuntime::class;
$_ENV['ENV_FILE_PATH'] ??= './env.yml';

// symfony default
require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

最佳实践

下次更新index.phpbin/console
index.php:

<?php

use App\Kernel;

// env.yml loader announcement, this will disable dotenv loader
$_SERVER['APP_RUNTIME'] = \Brannow\Component\Envyml\SymfonyRuntime::class;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    return new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);
};

bin/console:

#!/usr/bin/env php
<?php

use App\Kernel;
use Symfony\Bundle\FrameworkBundle\Console\Application;

if (!is_file(dirname(__DIR__).'/vendor/autoload_runtime.php')) {
    throw new LogicException('Symfony Runtime is missing. Try running "composer require symfony/runtime".');
}

// env.yml loader announcement, this will disable dotenv loader
$_SERVER['APP_RUNTIME'] = \Brannow\Component\Envyml\SymfonyRuntime::class;

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';

return function (array $context) {
    $kernel = new Kernel($context['APP_ENV'], (bool) $context['APP_DEBUG']);

    return new Application($kernel);
};

简单添加

$_SERVER['APP_RUNTIME'] = \Brannow\Component\Envyml\SymfonyRuntime::class;

之前

require_once dirname(__DIR__).'/vendor/autoload_runtime.php';