f2 / config
An interface for configuring and adapting all F2 components.
Requires (Dev)
- f2/asserty: ^1.0
README
Micro library that helps structuring application configuration, by enforcing and validating configuration files.
Creates a function:
F2\config($configName, ?callable $default, ?string $requiredInterface):mixed
Calling this function will parse a configuration file located in the path specified by env("CONFIG_ROOT"). Currently it only supports .php-files.
Usage Examples
<?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
);
Configuring
You can change the value mylibrary/some
in two ways
Via code
F2\globals('f2/config')["mylibrary/some"] = function() {
return new SomethingElse;
}
TIP! You can use the above method if you prefer configuration to be parsed from .yaml files or some other way.
Via .php files
If the environment variable CONFIG_ROOT is set, config will look for a file
named CONFIG_ROOT/mylibrary/some.php
and return the value.
TIP! If you don't want to provide the root for F2/config via the CONFIG_ROOT environment variable, you can override it by calling
globals("f2/config")["CONFIG_ROOT"] = '/some/alternative/root';
<?php return new SomethingElse();