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.
Getting a section
Sections are retrieved from the main config object by name:
$database = $config->getSection("database");
If the section does not exist, null is returned.
Reading values from a section
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.
Checking whether a key exists
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
}
Iterating over keys and values
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.
Using array-style access
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.
Converting to an array
If another API expects a plain array, call asArray().
$databaseConfig = $database?->asArray() ?? [];
This returns the internal key-value data of the section.
Creating modified copies
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.