f2 / config
1.0.4
2020-01-06 02:25 UTC
Requires (Dev)
- f2/asserty: ^1.0
README
这是一个微型库,通过强制和验证配置文件来帮助构建应用程序配置。
创建一个函数
F2\config($configName, ?callable $default, ?string $requiredInterface):mixed
调用此函数将解析位于 env("CONFIG_ROOT") 指定的路径中的配置文件。目前它只支持 .php 文件。
用法示例
<?php
namespace MyLibrary;
use function F2\config;
// Requires you to have a file CONFIG_ROOT/pdo.php that returns a PDO instance
$db = config("pdo");
// Looks for a file CONFIG_ROOT/pdo.php, but falls back to the return value from the callback
$db = config("pdo", function() {
return new PDO("mysql:host=localhost", "root", null);
});
/**
* Injectable function
*/
function foo($a) {
$implementation = config( "mylibrary/foo", function() {
return function($a) {
return $a;
};
}
return call_user_func($implementation, $a);
)
/**
* Injectable object
*/
$instance = config(
"mylibrary/some",
function() {
return new Something();
},
SomeInterface::class
);
配置
您可以通过两种方式更改 mylibrary/some
的值
通过代码
F2\globals('f2/config')["mylibrary/some"] = function() {
return new SomethingElse;
}
提示! 如果您更喜欢从 .yaml 文件或其他方式解析配置,可以使用上述方法。
通过 .php 文件
如果设置了环境变量 CONFIG_ROOT,config 将寻找名为 CONFIG_ROOT/mylibrary/some.php
的文件并返回值。
提示! 如果您不想通过 CONFIG_ROOT 环境变量提供 F2/config 的根目录,可以通过调用
globals("f2/config")["CONFIG_ROOT"] = '/some/alternative/root';
来覆盖它。
<?php return new SomethingElse();