devcirclede / attrenv
用于标记属性或类以便于 EnvReader 解析的库
0.3.0
2023-04-03 09:02 UTC
Requires
- php: ^8.1
- php-di/php-di: ^7.0
Requires (Dev)
- devcirclede/env-reader: *
- mockery/mockery: ^1.5
- overtrue/phplint: ^9.0
- phpunit/phpunit: ^10.0
- slevomat/coding-standard: ^8.8
- symfony/var-dumper: ^6.2
- vimeo/psalm: ^5.7
This package is auto-updated.
Last update: 2024-10-03 12:20:54 UTC
README
Attrenv - DevCircleDe/EnvReader 扩展
使用 Attrenv,您可以使用环境变量值实例化类。
安装
composer require devcirclede/attrenv
(建议您已安装EnvReader.)
描述
解析器使用属性名作为环境变量名。但您也可以向属性传递自定义的环境变量名。每个参数/属性都必须有类型提示,或者您必须在 EnvironmentValue 属性中声明类型。
EnvironmentValue 仅支持 EnvReader 支持的类型。
如果您已创建类,您可以使用属性解析器自动从环境变量中加载值并实例化您的类。
用法
使用 Attrenv
<?php use DevCircleDe\Attrenv\Attribute\EnvironmentValue; use DevCircleDe\Attrenv\Attrenv; class EnvConfiguredClass { #[EnvironmentValue] private string $secret; #[EnvironmentValue(envName: 'ENV_NAME')] private string $betterInternalName; #[EnvironmentValue(type: 'json', default: ['simple' => 'better'])] private array $configArrayJson; public function __construct( #[EnvironmentValue] private readonly string $databaseName, #[\SensitiveParameter] #[EnvironmentValue] string $secret, private readonly array $optional = [] ) { } } $envConfiguredClass = (new Attrenv())->getParser()->parse(EnvConfiguredClass::class);
您还可以使用自己的 EnvParser 实现。
创建自己的解析器并实现 DevCircleDe\Attrenv\Decorator\EnvParserInterface。
Attrenv 使用 php-di 包进行依赖注入。
为了自动加载配置,创建一个配置文件 DOCUMENT_ROOT/config/attrenv-config.php
<?php return [ 'DevCircleDe\Attrenv\Decorator\EnvParserInterface' => new CustomParser(), ];
如果您想手动加载,创建您的文件在任何您想要的位置并加载它
$envConfiguredClass = (new Attrenv('your/path/to/config.php'))->getParser()->parse(EnvConfiguredClass::class);