Zephyrus/Documentation/Configuration

Configuration

Your environment, in one place.

A Zephyrus application is configured by one YAML file, usually config.yml at the project root. Configuration::fromYamlFile() reads it, resolves !env tags, and returns an immutable tree of typed section objects. The configuration is strict: a key the framework does not know stops the boot, so a typo never turns into a silently ignored setting.

Load a file

use Zephyrus\Core\Config\Configuration;

$config = Configuration::fromYamlFile(__DIR__ . '/config.yml');

$config->application->environment; // Environment::Production
$config->session->name;            // 'APP_SESSION'
$config->security->maxBodySize;    // 2097152
$config->database?->host;          // 'localhost', or null when there is no database section

Six sections are built in. All of them are always present with safe defaults, except database and router, which are null when the file has no database: or router: key.

application:
  environment: !env APP_ENV, production
  debug: !env APP_DEBUG, false

session:
  name: APP_SESSION
  lifetime: 0                      # seconds; 0 ends with the browser
  idle_timeout: 1800
  http_only: true
  secure: auto                     # true, false or auto (secure when the request is https)
  same_site: Lax                   # Strict, Lax or None (None requires secure)

security:
  force_https: false
  allowed_hosts: [example.com]     # host names, optionally pinned to a port (example.com:443); no scheme; empty accepts every Host
  max_body_size: 2097152           # bytes, no unit suffix
  trusted_proxies: []              # addresses or CIDR network addresses
  csrf:
    enabled: true
    exceptions: ['#^/webhooks/#']  # quoted, anchored
  encryption:
    key: !env APP_ENCRYPTION_KEY
  headers:
    x_frame_options: DENY
    hsts_max_age: 31536000

localization:
  locale: en
  supported_locales: [en, fr]
  locale_path: locale              # relative to the base path given to the builder
  timezone: America/Toronto
  currency: CAD

database:
  host: !env DB_HOST, localhost
  port: !env DB_PORT, 5432
  database: !env DB_NAME, app
  username: !env DB_USERNAME, app
  password: !env DB_PASSWORD

router:
  controllers:                     # required: PSR-4 namespace => directory
    App\Controllers: app/Controllers
  middleware_groups:               # optional: name => middleware or group names
    admin: [auth, audit]
  cache: var/zephyrus/routes.php   # optional, this is the default

Keys are accepted in snake_case or camelCase (max_body_size or maxBodySize), one spelling per key. Besides the keys above, session accepts cookie_path, security accepts trusted_headers, localization accepts date_format, time_format, datetime_format and grouping_separator, and database accepts driver, charset, ssl_mode, ssl_root_cert and column_cache_version.

The router section declares where the controllers are, so the application needs no discoverControllers() call: see Routing. Its paths resolve against the base path, and no value in it may carry a YAML tag (!env included).

Nothing is applied just because it is declared. The builder wires localization, applies application.debug and localization.timezone, and refuses to boot when a security: key is not enforced by a middleware you mounted: see The application and Security.

Environment variables

!env NAME reads a variable. !env NAME, default falls back to the text after the comma when the variable is not set.

database:
  host: !env DB_HOST, localhost
  password: !env DB_PASSWORD

An unset variable without a default reads as null, which a required value then refuses. Every !env value is a string; section objects cast it (port: !env DB_PORT, 5432 becomes the integer 5432). Keep secrets such as passwords and encryption keys in the environment, never in the YAML file you commit.

The framework never reads a .env file. Load it yourself, before the configuration:

Dotenv\Dotenv::createImmutable(__DIR__)->safeLoad();

$config = Configuration::fromYamlFile(__DIR__ . '/config.yml');

Only $_ENV and the process environment are read, never $_SERVER. $_SERVER carries values a client can influence, so a variable set per request with Apache SetEnv or a fastcgi_param is not seen. Set it in the real process environment: the container environment, or env[NAME] in a php-fpm pool.

For the same reason, a variable name that a request or the web server can supply is refused, whatever its case. Calling env('HTTP_HOST') directly throws an InvalidArgumentException; the same name in a YAML file (debug: !env HTTP_HOST) throws a ConfigurationException whose message is prefixed with the tag and the key. The refused names are those starting with HTTP_, REDIRECT_, ORIG_, SSL_ or H2_, CGI and server names such as REMOTE_ADDR, QUERY_STRING, HTTPS or SERVER_NAME, and any name holding = or a NUL byte.

!env tag at "application.debug": the variable name is refused: names starting with HTTP_ can be set per request by the client request headers, so they are never read as configuration; rename the variable.

env('HTTP_HOST') gives the same reason after the name it was called with ("HTTP_HOST": names starting with HTTP_ ...). The !env message leaves the name out, because a value pasted where the name belongs (a base64 secret ends with =) would otherwise reach the logs. Version 0.16 quoted it.

The env() helper

env() is the same read for your own code. It returns the default when the variable is unset, and casts the strings true, false, null and empty (optionally in parentheses) to their native values.

$debug = env('APP_DEBUG', false);
$from = env('MAIL_FROM', 'no-reply@example.com');

Environments

application.environment accepts production (or prod), staging (or stage), testing (or test) and development (or dev, local), case-insensitively. Anything else, and an absent key, means production: the default is the strict one. The value is an Environment enum, and isProductionLike() is true for production and staging.

use Zephyrus\Core\Config\Environment;

Environment::fromString('local');               // Environment::Development
Environment::fromString('banana');              // Environment::Production
Environment::Staging->isProductionLike();       // true

application.debug defaults to true in development and testing, and to false in production and staging. In a production-like environment the application forces debug off whatever the file says: see Errors.

Strict validation

A key a built-in section does not know stops the boot with a ConfigurationException that names the closest accepted key, or lists the accepted ones:

Configuration section 'security' field 'max_bdy_size' is an unknown key: did you mean "max_body_size"?
Configuration section 'session' field 'max_body_size' is an unknown key: the accepted keys are name, lifetime, httpOnly, secure, sameSite, cookiePath, idleTimeout.
Configuration section 'security' sets both 'maxBodySize' and 'max_body_size': keep one.

A top-level key that is close to a built-in section name is refused as well:

Configuration key 'sesion' is not a known section: did you mean "session"? A section of your own needs a factory registered under its name in the $sectionFactories argument of the Configuration factories.

Values are checked too. Booleans accept only true/false, 1/0, on/off and yes/no, and sizes are numbers of bytes:

Configuration section 'application' field 'debug' has invalid value "maybe": is not a boolean; use true/false, 1/0, on/off or yes/no.
Configuration section 'security' field 'max_body_size' has invalid value "2M": must be a number of bytes, for example 2097152 (no unit suffix).

Read these as instructions: the message names the section, the key and what to change.

Your own sections

Any other top-level key is ignored unless you register a section for it. A section is a subclass of ConfigSection whose fromArray() reads typed values:

namespace App\Config;

use Zephyrus\Core\Config\ConfigSection;

final class BillingConfig extends ConfigSection
{
    public readonly string $provider;
    public readonly int $trialDays;

    // An override does not inherit #[\SensitiveParameter]: mark $values so the raw section stays out of a trace.
    public static function fromArray(#[\SensitiveParameter] array $values): static
    {
        $section = new static($values);
        $section->provider = $section->getString('provider', 'none');
        $section->trialDays = $section->getInt('trialDays', 30); // trial_days in YAML
        return $section;
    }
}
billing:
  provider: stripe
  trial_days: 14

Pass the class under the section name as the second argument, and read the section back with section():

$config = Configuration::fromYamlFile(
    __DIR__ . '/config.yml',
    ['billing' => BillingConfig::class],
);

$config->section('billing')->trialDays; // 14
$config->hasSection('billing');         // true

ConfigSection offers get(), getString(), getInt(), getFloat(), getBool(), getArray() and has(). Nested keys use dots (smtp.host), and both trialDays and trial_days find the same value. Secrets you declare in a $secretKeys property are masked by toArray(). When getInt(), getFloat(), getBool() or getString() (given an array) refuses the value of such a key, or of a key under it, the message shows [value] instead of the value.

The framework's own MailerConfig is a section of this kind, and so is the render: section. Both refuse an unknown key with the same message (version 0.14.1 ignored it):

Configuration section 'render' field 'cach' is an unknown key: did you mean "cache"?
Configuration section 'mailer' field 'smtp.hots' is an unknown key: did you mean "smtp.host"?

A dotted key written flat (smtp.host: mail.example.com directly under mailer:) is refused with the nested form to write instead:

Configuration section 'mailer' field 'smtp.host' is written flat: nest it under 'smtp', such as smtp: { host: ... }.

Register the mailer as ['mailer' => MailerConfig::class] to configure SMTP from YAML: see Mail.

Good to know

  • A custom section does not refuse unknown keys: a misspelled key there silently takes its default.
  • A factory registered under a built-in name (database or router, in any spelling), under a blank name, or two factories naming the same section throw InvalidArgumentException. For router the message is Section factory "router" collides with the built-in section "router"; read it with $configuration->router instead. An application with a section of its own called router renames it (routing, for instance).
  • A section named routes is refused as a typo of router: name yours routing or anything further from it.
  • section('database') also throws: read built-in sections through their typed property, $config->database.

Several files

When settings differ per machine, merge files. Later files override earlier ones, key by key. A list from a later file replaces the earlier list entirely, at any depth:

$config = Configuration::fromOptionalYamlFiles([
    __DIR__ . '/config.yml',
    __DIR__ . '/config.local.yml', // skipped when it does not exist
]);
Method Reads Missing file
fromYamlFile($path) one YAML file throws
fromYamlFiles($paths) several YAML files, merged throws
fromOptionalYamlFiles($paths) several YAML files, merged skipped
fromFile($path) one YAML file, or a PHP file returning an array throws
fromFiles($paths) several YAML or PHP files, merged throws
fromOptionalFiles($paths) several YAML or PHP files, merged skipped
fromArray($array) a nested array
defaults() nothing: every section uses its defaults

With trusted_proxies: [10.0.0.0/8, 0.0.0.0/0] in config.yml, a config.local.yml holding trusted_proxies: [10.1.2.3] gives [10.1.2.3], not a mix of both. A later [] empties the earlier list, and an empty allowed_hosts accepts any host: write it only when you mean it. Mappings still merge key by key, and a [] or {} over a mapping leaves it as it is. An empty section in a later file (security: with nothing under it, or null in a PHP file) changes nothing: to reset a setting, write it (csrf: {enabled: true}, trusted_proxies: []). In a PHP file, an array with non-contiguous integer keys (a filtered list) still replaces an earlier list ([2 => '10.9.9.9'] over ['10.0.0.1', '10.0.0.2', '10.0.0.3'] gives ['10.9.9.9']); only a filtered array over another filtered array (or over a mapping) merges key by key, so wrap a filtered list in array_values().

All of them take the custom section map as their last argument. They raise a ConfigurationException for a missing or unreadable file, a file that does not parse, a refused !env tag, and a file that breaks one of these rules:

  • Three extensions. fromFile(), fromFiles() and fromOptionalFiles() read only .yml, .yaml and .php files.
  • A local path only. A file, YAML or PHP, is read from a plain local path. A stream wrapper URL (file://, phar://, data:) is refused before the file is looked for, even as an optional file: pass /srv/app/config.yml, not file:///srv/app/config.yml.
  • A mapping of sections. A YAML scalar or list, or a PHP file that returns a list, is refused. An empty or comment-only YAML file reads as empty.
Configuration file not found: config.yml
Configuration file is not readable: config.yml
Configuration file config.yml: must be a mapping of sections
Configuration file settings.json: must be YAML (.yml, .yaml) or PHP (.php)
Configuration file must be a local path, not a stream wrapper URL (file://)
Failed to parse configuration file [config.yml]: invalid YAML near line 5 (the parser's detail is withheld, since it can quote a secret from the file).

The parse error never quotes the file, which can hold a password: open it at that line to see the mistake. Version 0.16 appended the parser's message, and ran a .json or extensionless file as PHP.

Caches and deployment

Two build artifacts spare a production request the work of reading the application: the parsed config.yml and, with a router: section, the compiled routes. Write them once, when the image is built:

vendor/bin/zephyrus cache:warm

It writes var/zephyrus/config.yml.php and, when config.yml declares router:, var/zephyrus/routes.php, and prints one Wrote <path> line per file (Wrote /var/www/html/var/zephyrus/routes.php (1 route)). --config=PATH (repeatable) warms another file: a relative path is read from the current directory, and the default is the config.yml at the project root. vendor/bin/zephyrus cache:clear deletes both files and exits 0 when they are already gone. Exit codes: 0 written, 1 refused (message on stderr), 2 usage error.

Configuration::fromYamlFile() reads var/zephyrus/<file name>.php beside the file when it matches the file's content, with no change to your code. The cache holds the YAML before any tag is resolved: !env is still read from the environment on every load and no environment value is written to disk, but the literal values of the file are copied as they are. In production and staging, Router::fromConfiguration() reads the routes cache (see Routing).

COPY . /var/www/html
RUN composer install --no-dev --optimize-autoloader && composer dump-autoload --optimize
RUN php vendor/bin/zephyrus cache:warm
USER www-data
  • Run it after COPY and composer dump-autoload (the controllers must be autoloadable), before any USER, and on a path no later chown touches.
  • The caches are PHP files the application includes, protected by their owner and file modes: the owner must be root or the owner of config.yml, and neither the file nor any directory between it and the application root (the root itself excluded) may be writable by group or others. A cache that fails the check is not included: one error_log line, then the YAML is parsed and the controllers are discovered. The warm refuses what it could not stand behind, for example Cannot write the boot cache <root>/var/zephyrus/config.yml.php: <root>/var is writable by its group or by others: run chmod g-w,o-w <root>/var.
  • The files live in var/zephyrus/, outside cache/ on purpose: an application that gives cache/ to www-data lets it rename a root-owned directory inside it and plant its own file.
  • Run it as root or as the owner of config.yml: any other user is refused, because the application would ignore what it writes.
  • The warm writes var/zephyrus/.gitignore (*) unless one is there. An image built by COPY . must also list var/zephyrus/ in .dockerignore, so that each image warms its own caches.
  • Before it writes anything the warm checks every configuration, its router: section, the process owner and every cache path: the directory guards (mode, owner, link), the regular-file check, and two caches landing on the same file (Two caches would be written to <root>/var/zephyrus/config.yml.php: give router.cache another path., exit 1). A refusal in a later --config leaves the earlier caches unwritten, and cache:clear checks every file before it deletes the first. A file at a cache path that the warm did not write is never replaced or deleted.
  • A config.yml that is a symbolic link is read under the directory of the link: its caches are var/zephyrus/config.yml.php and routes.php beside the link, where the application reads them. A cache that version 0.16 wrote beside the link target is no longer read: run cache:warm again.
  • router: is cached only from a config.yml at the application root. From --config=config/config.yml its relative paths resolve against config/, and a refusal ends with Note that router: is cached only from config.yml at the application root, and its paths were resolved against <root>/config.
  • A cache whose config.yml changed, or that another framework version wrote, is ignored with one error_log line:
Zephyrus: ignored the boot cache /var/www/html/var/zephyrus/config.yml.php: it is stale, its source changed after it was written. Run vendor/bin/zephyrus cache:warm to rebuild it, or vendor/bin/zephyrus cache:clear to remove it.

Without the warm, production and staging still work: the YAML is parsed and the controllers discovered on every request. On an application of about 340 routes with OPcache, the two caches save about 6 to 7 ms per request (routes from 6-8 ms to 1.3-1.6 ms, configuration from about 2 ms to about 1 ms).

Reading values anywhere

Pass the Configuration to the builder and it becomes available through App::getConfiguration() and the config() helper:

config('security', 'maxBodySize');  // 2097152
config('billing', 'trialDays', 30); // a custom section, with a default
config('database');                 // the typed DatabaseConfig, or null

config() returns the default you pass when no configuration was set or the property is missing. It throws for a built-in section spelled any way but the exact name (config('Database')).

$config->toArray() exports the tree for inspection. Secrets (the database password, the encryption key, the mailer password) are replaced by [redacted] unless you pass true, which belongs nowhere near a debug panel or a log.

Bootstrap variables

For deployments that choose their configuration from the environment, ApplicationBootstrap::fromEnvironment() builds an Application from a directory of PHP configuration files:

Variable Meaning Default
APP_CONFIG_DIR directory holding the files ./config
APP_CONFIG_BASE base file name app
APP_ENV environment suffix none
APP_CONFIG_EXTRA comma-separated extra suffixes none

It requires <dir>/<base>.php, then merges <base>.local.php, <base>.<APP_ENV>.php and each <base>.<extra>.php when they exist. With APP_ENV=stage, config/app.php is read, then config/app.stage.php overrides it. These files return arrays and follow the same strict rules. An environment or base name holding a path separator is refused.

use Zephyrus\Core\Bootstrap\ApplicationBootstrap;

$app = ApplicationBootstrap::fromEnvironment();
$response = $app->handle($request);

The same class offers fromConfigDirectory(), fromConfigurationFile(), fromConfigurationArray() and fromConfigFiles() when you pass the paths yourself. An application with its own bootstrap class, as in The application, does not need any of them.

Good to know

  • Booleans written in !env need a default: debug: !env APP_DEBUG, false. An unset variable without one reads as null, and a boolean setting refuses null.
  • allowed_hosts: [] accepts every host. An empty string or null is refused.
  • security.csrf, security.encryption and security.headers must be mappings (csrf: { enabled: false }).
  • security.max_body_size is bytes, an integer or a string of digits. 2M and 1.5 are refused.
  • build() also sets the timezone from localization.timezone, which defaults to UTC.
↑ ↓ NAVIGATE   ↵ OPENTHE ZEPHYRUS FIELD GUIDE