Skip to content
rootsPublic

About

Fluent configuration management for WordPress

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

61 stars

Watchers

8 watching

Forks

Latest commit

 

History

64 Commits

Folders and files

Repository files navigation

wp-config

Build Status Packagist Downloads Follow Roots Sponsor Roots

Fluent configuration management for WordPress

$config = Config::make($rootDir)->bootstrapEnv();

$config
    ->env('WP_ENV', 'production')
    ->env('WP_HOME')
    ->env('WP_SITEURL', fn ($config) => $config->get('WP_HOME') . '/wp')
    ->when($config->get('WP_ENV') === 'development', fn ($config) => $config->set([
        'WP_DEBUG' => true,
        'SAVEQUERIES' => true,
    ]))
    ->required('WP_HOME')
    ->apply();
  • Fluent API for clean, chainable configuration
  • Environment variables loaded from .env files with vlucas/phpdotenv, converted like Laravel's env()
  • Conditional configuration with when()
  • Lazy values, resolved when read or applied
  • Required values, checked before anything is defined
  • Hooks, and Config::extend() for packages

Support us

Roots is an independent open source org, supported only by developers like you. Your sponsorship funds WP Packages and the entire Roots ecosystem, and keeps them independent. Support us by purchasing Radicle or sponsoring us on GitHub — sponsors get access to our private Discord.

Requirements

  • PHP >= 8.3
  • Composer

Installation

composer require roots/wp-config:^2.0

Usage

Basic configuration

use Roots\WPConfig\Config;

$config = Config::make($rootDir)->bootstrapEnv();

$config
    ->set('WP_DEBUG', true)
    ->env('WP_HOME')
    ->apply();

set() and env() collect values, and apply() defines them all as constants at once. $rootDir is the directory that holds your .env files.

Environment variables

bootstrapEnv() loads .env and then .env.local from the root directory, skipping files that don't exist. Variables already set in the real environment win over the files, and .env.local wins over .env. Pass other file names to load those instead: bootstrapEnv(['.env', '.env.testing']).

env() sets a value from the environment variable of the same name, falling back to a default when the variable isn't set:

$config
    ->env('DB_NAME')
    ->env('DB_HOST', 'localhost')
    ->env(['DB_USER', 'DB_PASSWORD', 'DB_PREFIX' => 'wp_']);

In an array, a plain entry is a variable name, and a string key gives that variable its own default. env(['DB_HOST', 'localhost']) reads two variables, DB_HOST and localhost; write env(['DB_HOST' => 'localhost']) instead.

getEnv() reads a variable without setting a value:

$table_prefix = $config->getEnv('DB_PREFIX') ?: 'wp_';

Use it instead of reading $_ENV directly. $_ENV is empty for variables from the real environment when PHP's variables_order setting leaves out E, as php.ini-production does. env() and getEnv() read $_SERVER, then $_ENV, then getenv(), and convert values the same way as Laravel's env() helper:

Value Result
true, (true) true
false, (false) false
null, (null) null
empty, (empty) ''
"quoted", 'quoted' quoted
anything else the string as-is, so 0123 stays '0123'

Matching ignores case, so TRUE and Null are converted too. Defaults aren't converted.

Conditional configuration

when() runs a callback when its condition is truthy, and an optional second callback when it isn't. Callbacks receive the Config instance and the condition's value:

$config
    ->env('WP_ENV', 'production')
    ->when($config->get('WP_ENV') === 'development', fn ($config) => $config->set([
        'WP_DEBUG' => true,
        'SAVEQUERIES' => true,
        'SCRIPT_DEBUG' => true,
    ]))
    ->when(
        $config->getEnv('REDIS_HOST'),
        fn ($config, $host) => $config->set('WP_REDIS_HOST', $host),
        fn ($config) => $config->set('WP_REDIS_DISABLED', true),
    );

set() overwrites earlier values, so a when() block can override defaults set above it.

Lazy values

A closure passed to set() or setDefault(), or as an env() default, is a lazy value. It's called with the Config instance when the value is read, including when apply() defines the constants, so it reflects values set later, even in before_apply hooks:

$config
    ->env('WP_HOME')
    ->env('WP_SITEURL', fn ($config) => $config->get('WP_HOME') . '/wp')
    ->set('WP_CONTENT_URL', fn ($config) => $config->get('WP_HOME') . '/content');

Before apply(), each read calls the closure again, since the values it depends on can still change. apply() calls each lazy value once, even when other lazy values read it, and get() returns that value afterward. A lazy value can read the config but not change it. To define a constant whose value is a closure, wrap it: set('KEY', fn () => $closure).

Required values

required() makes apply() throw MissingConfigException, listing every missing key, if any of them isn't set or is null or ''. Nothing is defined when it throws:

$config
    ->env(['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'WP_HOME'])
    ->required(['DB_NAME', 'DB_USER', 'WP_HOME']);

Don't require values that can legitimately be empty, such as a local DB_PASSWORD.

Defaults and existing constants

setDefault() sets a value only if it isn't set yet or is null, like ??=:

$config->setDefault('WP_ENVIRONMENT_TYPE', $config->getEnv('WP_ENVIRONMENT_TYPE', 'production'));

If a constant with that name was already defined, for example by a host's prepend file or a test bootstrap, setDefault() keeps its value. set() doesn't: apply() throws ConstantAlreadyDefinedException for every constant that's already defined with a different value, and defines nothing. Constants already defined with the same value are fine. Values are compared strictly, so 1 and true conflict.

Reading values

$config->get('WP_HOME');              // throws UndefinedConfigKeyException if it isn't set
$config->get('WP_ENV', 'production'); // with a default
$config->has('WP_HOME');              // true even if the value is null
$config->all();                       // every value, with lazy values resolved

Hooks

Register callbacks with addAction() and run them with doAction():

$config->addAction('security_setup', fn ($config) => $config->set([
    'FORCE_SSL_ADMIN' => true,
    'DISALLOW_FILE_EDIT' => true,
]));

$config->doAction('security_setup');

Callbacks run in priority order, lowest first (default 10), and receive the Config instance plus any arguments passed to doAction().

apply() fires two hooks itself, and doAction() throws ReservedHookException for either:

  • before_apply runs before anything is checked or defined, so its callbacks can still change the config.
  • after_apply runs once the constants are defined. Its callbacks can read the config but not change it, and an exception they throw propagates after the constants are defined. It doesn't run if apply() fails.

Once apply() succeeds, the config can't be changed or applied again: doing so throws ConfigAlreadyAppliedException.

Packages

A package can't reach the Config instance a project creates. Instead, it registers a callback with Config::extend() from a Composer autoload.files script, and every new Config instance runs it.

Extensions run when the instance is created, before bootstrapEnv() loads .env files and before the project's config, so values from .env files aren't available yet. Do the work in a before_apply hook instead, and use setDefault() so the project's values win. setDefault() also fills a value the project's env() left null because the variable isn't set:

use Roots\WPConfig\Config;

Config::extend(function (Config $config) {
    $config->addAction('before_apply', function (Config $config) {
        $config->setDefault('COOKIE_DOMAIN', $config->getEnv('COOKIE_DOMAIN', false));
    });
});

A package's hooks are added first, so at the same priority they run before the project's own before_apply hooks. To override a package default from a hook, use set() rather than setDefault(). To keep a package default from applying, set false or ''.

In tests, Config::flushExtensions() removes registered extensions.

Full example

A Bedrock-style project with this structure:

├── composer.json
├── config.php          # WordPress configuration
├── .env
├── wp-cli.yml          # path: public/wp
├── vendor/
└── public/             # Document root
    ├── content/        # WP_CONTENT_DIR: mu-plugins, plugins, themes, uploads
    ├── index.php
    ├── wp-config.php   # Loads config.php
    └── wp/             # WordPress core

Install WordPress core into public/wp with roots/wordpress and "extra": {"wordpress-install-dir": "public/wp"} in composer.json. It doesn't include any themes, so install one into public/content/themes.

public/wp-config.php loads Composer, the configuration and WordPress. Keep wp-settings.php in this file: WP-CLI refuses to run if wp-config.php doesn't load it directly.

<?php

require_once dirname(__DIR__) . '/vendor/autoload.php';
require_once dirname(__DIR__) . '/config.php';
require_once ABSPATH . 'wp-settings.php';

public/index.php loads WordPress from its subdirectory:

<?php

define('WP_USE_THEMES', true);
require __DIR__ . '/wp/wp-blog-header.php';

wp-cli.yml points WP-CLI at WordPress core, so wp works from the project root:

path: public/wp

.env:

WP_ENV=development
WP_HOME=https://example.test

DB_NAME=example
DB_USER=example
DB_PASSWORD=secret
# DB_HOST=localhost
# DB_PREFIX=wp_
# Or instead of DB_NAME, DB_USER, DB_PASSWORD and DB_HOST:
# DATABASE_URL=mysql://user:password@localhost:3306/example

# Set only if every request reaches PHP through a proxy that overwrites X-Forwarded-Proto
# TRUST_PROXY_HEADERS=true

AUTH_KEY='generateme'
SECURE_AUTH_KEY='generateme'
LOGGED_IN_KEY='generateme'
NONCE_KEY='generateme'
AUTH_SALT='generateme'
SECURE_AUTH_SALT='generateme'
LOGGED_IN_SALT='generateme'
NONCE_SALT='generateme'

config.php:

<?php

use Roots\WPConfig\Config;

$rootDir = __DIR__;
$webrootDir = "{$rootDir}/public";

$config = Config::make($rootDir)->bootstrapEnv();

$config
    /**
     * Environment
     */
    ->env('WP_ENV', 'production')
    ->setDefault('WP_ENVIRONMENT_TYPE', $config->getEnv('WP_ENVIRONMENT_TYPE', $config->get('WP_ENV')))

    /**
     * URLs
     */
    ->env('WP_HOME')
    ->env('WP_SITEURL', fn ($config) => $config->get('WP_HOME') . '/wp')

    /**
     * Content directory
     */
    ->set([
        'CONTENT_DIR' => '/content',
        'WP_CONTENT_DIR' => fn ($config) => $webrootDir . $config->get('CONTENT_DIR'),
        'WP_CONTENT_URL' => fn ($config) => $config->get('WP_HOME') . $config->get('CONTENT_DIR'),
    ])

    /**
     * Database
     */
    ->env(['DB_NAME', 'DB_USER', 'DB_PASSWORD', 'DB_HOST' => 'localhost'])
    ->set([
        'DB_CHARSET' => 'utf8mb4',
        'DB_COLLATE' => '',
    ])
    ->when(
        (bool) $config->getEnv('DATABASE_URL'),
        function ($config) {
            // Read the URL here, not through when(), to keep it out of stack traces
            $dsn = parse_url($config->getEnv('DATABASE_URL'));

            if (! isset($dsn['host'])) {
                throw new InvalidArgumentException(
                    'DATABASE_URL must look like mysql://user:password@host:3306/database. Percent-encode special characters in the user and password.',
                );
            }

            $config->set([
                'DB_NAME' => rawurldecode(ltrim($dsn['path'] ?? '', '/')),
                'DB_USER' => rawurldecode($dsn['user'] ?? ''),
                'DB_PASSWORD' => rawurldecode($dsn['pass'] ?? ''),
                'DB_HOST' => isset($dsn['port']) ? "{$dsn['host']}:{$dsn['port']}" : $dsn['host'],
            ]);
        },
    )

    /**
     * Authentication unique keys and salts
     */
    ->env([
        'AUTH_KEY', 'SECURE_AUTH_KEY', 'LOGGED_IN_KEY', 'NONCE_KEY',
        'AUTH_SALT', 'SECURE_AUTH_SALT', 'LOGGED_IN_SALT', 'NONCE_SALT',
    ])

    /**
     * Custom settings
     */
    ->set([
        'AUTOMATIC_UPDATER_DISABLED' => true,
        'DISALLOW_FILE_EDIT' => true,
        'DISALLOW_FILE_MODS' => true,
        'CONCATENATE_SCRIPTS' => false,
    ])
    ->env([
        'DISABLE_WP_CRON' => false,
        'WP_POST_REVISIONS' => true,
    ])

    /**
     * Debug settings
     */
    ->env('WP_DEBUG', false)
    ->set([
        'WP_DEBUG_DISPLAY' => false,
        'WP_DEBUG_LOG' => false,
        'SCRIPT_DEBUG' => false,
    ])

    /**
     * Development overrides
     */
    ->when($config->get('WP_ENV') === 'development', fn ($config) => $config->set([
        'SAVEQUERIES' => true,
        'WP_DEBUG' => true,
        'WP_DEBUG_DISPLAY' => true,
        'WP_DEBUG_LOG' => true,
        'WP_DISABLE_FATAL_ERROR_HANDLER' => true,
        'SCRIPT_DEBUG' => true,
        'DISALLOW_FILE_MODS' => false,
    ]))

    /**
     * Detect HTTPS behind a reverse proxy or load balancer. Clients can send
     * X-Forwarded-Proto themselves, so trust it only when TRUST_PROXY_HEADERS
     * says every request comes through a proxy that overwrites it.
     */
    ->when(
        $config->getEnv('TRUST_PROXY_HEADERS') && ($_SERVER['HTTP_X_FORWARDED_PROTO'] ?? null) === 'https',
        function () {
            $_SERVER['HTTPS'] = 'on';
        },
    )

    ->required(['WP_HOME', 'DB_NAME', 'DB_USER'])
    ->apply();

ini_set('display_errors', WP_DEBUG_DISPLAY ? '1' : '0');

$table_prefix = $config->getEnv('DB_PREFIX') ?: 'wp_';

if (! defined('ABSPATH')) {
    define('ABSPATH', "{$webrootDir}/wp/");
}

DATABASE_URL replaces DB_NAME, DB_USER, DB_PASSWORD and DB_HOST when it's set. Percent-encode special characters in the user and password, such as #, / and ?. Query parameters such as ?ssl-mode=REQUIRED are ignored, so set MYSQL_CLIENT_FLAGS yourself for SSL. For a socket, use DB_HOST instead.

Upgrading from v1

Replace static calls

v1 used static methods on a global configuration. v2 uses an instance:

// Before
Config::define('WP_DEBUG', true);
Config::define('WP_HOME', env('WP_HOME'));
Config::apply();

// After
Config::make($rootDir)
    ->bootstrapEnv()
    ->set('WP_DEBUG', true)
    ->env('WP_HOME')
    ->apply();

Code outside the config file that called Config::get() at runtime, such as in a theme or plugin, should read the constants instead.

Consolidate environment files

Move overrides from config/environments/{env}.php into when() blocks in a single config file:

// Before: config/environments/development.php
Config::define('WP_DEBUG', true);
Config::define('SAVEQUERIES', true);

// After
$config
    ->env('WP_ENV', 'production')
    ->when($config->get('WP_ENV') === 'development', fn ($config) => $config->set([
        'WP_DEBUG' => true,
        'SAVEQUERIES' => true,
    ]));

Replace Dotenv and oscarotero/env

bootstrapEnv() replaces the Dotenv setup. Unlike Bedrock v1, it loads .env.local even when there's no .env. env() and getEnv() replace Env\env(), so you can composer remove oscarotero/env once nothing else, such as a theme or mu-plugin, calls Env\env(). Delete Bedrock's Env\Env::$options block too, since it fails once the package is gone, along with the now-unused use function Env\env;.

Use required() in place of $dotenv->required(), but note that it also rejects '', so don't require values that can be empty, such as a local DB_PASSWORD.

env() falls back to its default only when the variable isn't set, not when it's empty:

// Before: an empty DB_HOST= falls back to localhost
Config::define('DB_HOST', env('DB_HOST') ?: 'localhost');

// After: an empty DB_HOST= stays ''
$config->env('DB_HOST', 'localhost');

Values are read and converted like Laravel's env(), which differs from Bedrock v1's oscarotero/env settings:

  • Digit-only values such as 0123 stay strings. v1's CONVERT_INT turned them into integers. WordPress casts the numeric constants it reads, such as WP_POST_REVISIONS; cast values your own code needs as numbers.
  • empty and the parenthesized forms such as (true) are converted.
  • v1 read only getenv(), preferring the PHP process's environment over web server variables. v2 reads $_SERVER and $_ENV first, so a variable set both ways may resolve differently.

Move wp-settings.php

If config.php (or config/application.php) ends by loading wp-settings.php, move that line to wp-config.php, as in the full example.

Behavior changes

  • Config::define() is now set(). v1 threw as soon as you defined a constant that already existed; v2 checks every value in apply() and lists all the conflicts. Replace if (! defined('KEY')) { Config::define('KEY', ...); } with setDefault('KEY', ...).
  • Config::remove() has been removed. Use when() blocks to set values conditionally.
  • apply() can only succeed once per Config instance. Changing the config or calling apply() again afterward throws ConfigAlreadyAppliedException.
  • Closures passed to set() are lazy values instead of being defined as the constant's value.
  • Bedrock v1 trusted X-Forwarded-Proto from any client. The full example trusts it only when TRUST_PROXY_HEADERS is set, so set it behind a load balancer or proxy that overwrites the header.

API reference

Config

__construct(string $rootDir)

Creates a new Config instance for the project root, and runs the registered extensions against it.

static make(string $rootDir): static

Creates a new Config instance with a fluent-friendly named constructor.

static extend(callable $extension): void

Registers a callback that runs against every Config instance created afterward, in the order registered. See Packages.

static flushExtensions(): void

Removes all registered extensions.

bootstrapEnv(array $files = ['.env', '.env.local']): static

Loads environment variables from the given files in the root directory, skipping files that don't exist. Variables already in the environment take precedence, and later files override earlier ones.

getEnv(string $key, mixed $default = null): mixed

Reads and converts an environment variable without setting a value. Returns $default if it isn't set; a closure default is called with no arguments.

env(string|array $key, mixed $default = null): static

Sets a value from the environment variable of the same name, or $default if it isn't set. A closure default is a lazy value. Pass an array to read several: plain entries use $default, and string keys give their own default: env(['DB_NAME', 'DB_HOST' => 'localhost']).

set(string|array $key, mixed $value = null): static

Sets a value, or an associative array of values, overwriting earlier values. A closure is a lazy value.

setDefault(string|array $key, mixed $value = null): static

Sets a value only if it isn't set yet or is null, like ??=. A closure is a lazy value. If a constant with that name was already defined, its value is used instead.

get(string $key, mixed $default = null): mixed

Gets a value, resolving a lazy value. Returns $default if the key isn't set and a default is given, and throws UndefinedConfigKeyException otherwise.

has(string $key): bool

Returns whether a value is set, even if it's null.

all(): array

Returns all values, keyed by name, with lazy values resolved.

required(string|array $keys): static

Makes apply() throw MissingConfigException if any of the keys isn't set, or is null or ''. The check runs after before_apply hooks. It checks config values, not constants defined elsewhere, unless setDefault() picked them up.

when(mixed $condition, callable $callback, ?callable $default = null): static

Runs $callback when the condition is truthy, or $default when it isn't. A Closure condition is called with the Config instance. Callbacks receive the Config instance and the condition's value, and their return values are ignored.

addAction(string $tag, callable $callback, int $priority = 10): static

Registers a hook callback, run by doAction(), or by apply() for before_apply and after_apply.

doAction(string $tag, mixed ...$args): static

Runs the callbacks for a hook in priority order. Throws ReservedHookException for before_apply and after_apply.

apply(): void

Runs before_apply hooks, resolves lazy values, checks required values and conflicting constants, defines the constants, and runs after_apply hooks. Nothing is defined if a check fails.

Exceptions

These all implement Roots\WPConfig\Exceptions\WPConfigException, so you can catch them together. bootstrapEnv() lets phpdotenv's exceptions through, such as for a malformed .env file. Those implement Dotenv\Exception\ExceptionInterface.

  • ConfigAlreadyAppliedException: Thrown when changing the config or calling apply() after apply() succeeded, or calling apply() from a hook while it runs
  • ConstantAlreadyDefinedException: Thrown by apply() when constants are already defined with different values
  • InvalidConfigKeyException: Thrown when a key isn't a valid constant name, e.g. set(['KEY', 'value']) instead of set(['KEY' => 'value'])
  • LazyValueException: Thrown when lazy values depend on themselves or try to change the config
  • MissingConfigException: Thrown by apply() when a value marked with required() is missing or empty
  • ReservedHookException: Thrown when doAction() is called with before_apply or after_apply
  • UndefinedConfigKeyException: Thrown when getting a value that isn't set without a default

Community

Keep track of development and community news.

About

Fluent configuration management for WordPress

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

61 stars

Watchers

8 watching

Forks

Releases

Sponsor this project

Packages

Used by

Contributors

Languages