horat1us / environment-config
环境配置类
1.5.0
2022-10-21 13:30 UTC
Requires
- php: >=7.4
Requires (Dev)
- phpunit/phpunit: ^9.5
- squizlabs/php_codesniffer: ^3.7
README
一个简单的类,通过前缀使用 `getenv` 函数提供配置。
兼容性:已在 PHP 7.1 和 PHP 8.1 上测试
安装
使用 composer
composer require horat1us/environment-config
用法
实现自己的配置类
<?php namespace App; use Horat1us\Environment; class Config extends Environment\Config { public function getTimeout(): int { return $this->getEnv($key = 'APP_TIMEOUT', $default = 10); } public function getSlow(): string { // default can be instance of \Closure or callable array, like [$this, 'calculate'] return $this->getEnv($key = 'APP_KEY', $default = function(): string { return 'some-string'; // slow operation, may be fetching from DB }); } public function getNullValue(): ?string { /** * if you want to return null instead of throwing exceptio * if no environment variable found */ return $this->getEnv('KEY', [$this, 'null']); } public function getName(): string { return $this->getEnv($key = 'APP_NAME'); } }
然后使用它
<?php use App; $config = new App\Config("PREFIX_"); $config->getTimeout(); // 10 putenv("PREFIX_APP_TIMEOUT=5"); $config->getTimeout(); // 5 $config->getSlow(); // some-string // MissingEnvironmentException will be thrown because no default value provided $config->getName();
魔法特性
您可以使用 MagicTrait 定义自己的配置键和方法
<?php use Horat1us\Environment; class Config { use Environment\MagicTrait { getEnvironment as public getHost; } protected function getEnvironmentKeyPrefix(): string { return 'TEST_'; } } $config = new Config; $config->getHost(); // TEST_HOST environment key will be used to get value
注意:您的环境获取器应该以 get 开头,并且使用驼峰命名法