n7 / configs
配置文件组织库
v1.0.3
2021-03-14 18:46 UTC
Requires
- php: ~7.4|~8.0
Requires (Dev)
- phpunit/php-code-coverage: ^9.2
- phpunit/phpunit: ^9.5
This package is auto-updated.
Last update: 2024-09-15 02:53:25 UTC
README
通常,PHP项目的配置文件以数组形式存储在PHP文件中,或存储在YAML文件中。我在这类方法中看到了一些缺点
- 如果您的服务需要某些配置,您必须注入所有配置。
- 这些配置的结构不利于静态分析。
这个小型库为组织配置文件提供了一种稍微不同的方法。
常规配置文件
<?php return [ 'application' => [ 'timezone' => env('APPLICATION_TIMEZONE', 'UTC'), 'currency' => env('APPLICATION_CURRENCY', 'USD'), ], 'storage' => [ 'driver' => env('STORAGE_DRIVER', 'local'), 'drivers' => [ 'aws' => [ // ... ], 'local' => [ // ... ], ], ], ];
使用方法如下
<?php class LocalStorageAdapter { private Config $config; public function __construct(Config $config) { $this->config = $config; } public function build() { // IDE's autocomplete not working for this line $this->config->storage->drivers->local; } }
可以转换为
use N7\Configs\AbstractConfig; class ApplicationConfiguration extends AbstractConfig { private string $timezone; private string $currency; public function __construct() { $this->timezone = $this->env()->getString('APPLICATION_TIMEZONE', 'UTC'); $this->currency = $this->env()->getString('APPLICATION_CURRENCY', 'USD'); } } class StorageConfiguration extends AbstractConfig { private string $driver; private array $drivers = []; // If you want you are able to inject nested configurations public function __construct( LocalStorageConfiguration $localStorageConfiguration, AwsStorageConfiguration $awsStorageConfiguration ) { $this->driver = $this->env()->getString('STORAGE_DRIVER', 'local'); $this->drivers['local'] = $localStorageConfiguration; $this->drivers['aws'] = $awsStorageConfiguration; } } class LocalStorageConfiguration extends AbstractConfig { // ... public function __construct() { // ... } } class AwsStorageConfiguration extends AbstractConfig { // ... public function __construct() { // ... } }
现在您能够只注入所需的配置,并且这些配置的结构完全透明。
<?php class LocalStorageAdapter { private LocalStorageConfiguration $config; public function __construct(LocalStorageConfiguration $config) { $this->config = $config; } public function build() { $this->config; } }
文档
可用方法
public function getBool(string $key, $default = null): bool
public function getNullableBool(string $key, $default = null): ?bool
public function getFloat(string $key, $default = null): float
public function getNullableFloat(string $key, $default = null): ?float
public function getInt(string $key, $default = null): int
public function getNullableInt(string $key, $default = null): ?int
public function getList(string $key, $default = []): array
public function getNullableList(string $key, $default = []): ?array
public function getString(string $key, $default = null): string
public function getNullableString(string $key, $default = null): ?string
public function getRaw(string $key)
🥔