-
-
Notifications
You must be signed in to change notification settings - Fork 1
Working with Config Sections
A ConfigSection represents one named group of config values such as [database], [app] or [stripe].
Working with sections is useful when a class needs several related values but should not be handed the entire config object.
Sections are retrieved from the main config object by name:
$database = $config->getSection("database");If the section does not exist, null is returned.
Once we have a section, individual keys can be accessed without dot notation.
$host = $database?->get("host");
$port = $database?->getInt("port");Like Config, each section also supports typed getters from PHP.Gt/TypeSafeGetter.
Sometimes null is a valid outcome from get(), so it is useful to check explicitly whether a key exists.
if($database && $database->contains("password")) {
// password was defined
}ConfigSection implements IteratorAggregate, so it can be looped over directly.
foreach($database as $key => $value) {
echo "$key = $value", PHP_EOL;
}This is useful when copying a section into another object or displaying configuration for diagnostics.
Sections also implement ArrayAccess, so values can be read using array syntax.
echo $database["host"];The section remains immutable, so writing or unsetting values using array syntax will throw an exception.
If another API expects a plain array, call asArray().
$databaseConfig = $database?->asArray() ?? [];This returns the internal key-value data of the section.
ConfigSection is immutable. To add or replace a value, use with() to create a new section instance.
$newDatabase = $database->with("port", "3307");The original section is unchanged, and the returned section contains the updated value.
This immutability is what allows Config::withMerge() to build combined configurations without mutating earlier objects.
Once we know how to read configuration, the final piece is Generating config files.
PHP.GT/Config is a separately maintained component of PHP.GT/WebEngine.