roots/wp-config 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

roots/wp-config

Composer 安装命令:

composer require roots/wp-config

包简介

Fluent configuration management for WordPress

README 文档

README

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')
    ->set('WP_DEBUG', true)
    ->when($config->get('WP_ENV') === 'development', function($config) {
        $config
            ->set('SAVEQUERIES', true)
            ->set('SCRIPT_DEBUG', true);
    })
    ->apply();
  • Fluent API for clean, chainable configuration
  • Built-in environment variable loading via vlucas/phpdotenv
  • Conditional configuration with when()
  • Instance-scoped hook system for extensible configuration

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.1
  • 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)
    ->set('WP_HOME', 'https://example.com')
    ->apply();

Conditional configuration

$config
    ->env('WP_ENV', 'production')
    ->when($config->get('WP_ENV') === 'development', function($config) {
        $config
            ->set('WP_DEBUG', true)
            ->set('SAVEQUERIES', true)
            ->set('SCRIPT_DEBUG', true);
    });

Accessing values

$home = $config->get('WP_HOME');

// With a default value (no exception if key is missing)
$env = $config->get('WP_ENV', 'production');

$config
    ->set('WP_SITEURL', $config->get('WP_HOME') . '/wp')
    ->apply();

Environment variables

The Config class includes built-in support for loading environment variables:

$config->bootstrapEnv(); // Loads .env and .env.local files

$config
    ->env('DB_NAME')
    ->env('DB_USER')
    ->env('DB_HOST', 'localhost')
    ->apply();

Hook system

The Config class includes an instance-scoped hook system for extensible configuration:

// Register a hook
$config->addAction('security_setup', function($config) {
    $config->set('FORCE_SSL_ADMIN', true);
    $config->set('DISALLOW_FILE_EDIT', true);
});

// Execute the hook
$config
    ->set('WP_ENV', 'production')
    ->doAction('security_setup')
    ->apply();

Automatic before_apply hook

The Config class automatically executes any before_apply hooks when apply() is called. This enables packages to register configuration logic that runs automatically without requiring manual hook calls:

// Package authors can register automatic configuration
$config->addAction('before_apply', function($config) {
    // This runs automatically when apply() is called
    $config->set('AUTOMATIC_CONFIG', 'set by package');
});

// Users just need to call apply() - no manual hook management required
$config
    ->env('WP_HOME')
    ->set('WP_SITEURL', $config->get('WP_HOME') . '/wp')
    ->apply(); // Automatically runs all before_apply hooks

Upgrading from v1

Step 1: Update composer.json

{
  "require": {
    "roots/wp-config": "^2.0"
  }
}

Step 2: Replace static calls

Before:

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

After:

$config = Config::make($rootDir);
$config
    ->set('WP_DEBUG', true)
    ->env('WP_HOME')
    ->apply();

Step 3: Consolidate environment files

Before:

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

// config/application.php
Config::define('WP_HOME', env('WP_HOME'));
Config::apply();

After:

$config
    ->env('WP_ENV', 'production')
    ->env('WP_HOME')
    ->when($config->get('WP_ENV') === 'development', function($config) {
        $config
            ->set('WP_DEBUG', true)
            ->set('SAVEQUERIES', true);
    })
    ->apply();

Step 4: Update environment loading

Before:

$dotenv = Dotenv::createImmutable($rootDir);
$dotenv->load();

After:

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

Step 5: Update hook usage

Hooks are now instance methods instead of static methods:

Before:

Config::add_action('before_apply', function($config) { ... });

After:

$config->addAction('before_apply', function($config) { ... });

Removed APIs

  • Config::remove() has been removed. Use when() blocks to conditionally set values instead.
  • set() now overwrites previous values for the same key (useful in when() blocks for overriding defaults).

API reference

Config class

__construct(string $rootDir)

Creates a new Config instance with the specified root directory.

make(string $rootDir): static

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

bootstrapEnv(): self

Loads environment variables from .env files.

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

Sets a configuration value. Accepts a key/value pair or an associative array. Overwrites existing config map entries. Throws ConstantAlreadyDefinedException if a PHP constant with that name already exists.

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

Sets a configuration value from an environment variable. Falls back to $default if the variable is not set.

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

Gets a configuration value. Returns $default if the key is not set and a default is provided. Throws UndefinedConfigKeyException if the key is not set and no default is provided.

when(bool|Closure $condition, callable $callback): self

Conditionally executes configuration logic. The condition can be a boolean or a Closure that receives the Config instance.

apply(): void

Applies all configuration values by defining constants. Automatically runs before_apply hooks first.

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

Adds a hook callback that can be executed later with doAction(). Returns $this for chaining.

doAction(string $tag, ...$args): self

Executes all callbacks registered for the specified hook. Returns $this for chaining.

Exceptions

  • ConstantAlreadyDefinedException: Thrown when attempting to redefine a constant
  • UndefinedConfigKeyException: Thrown when accessing an undefined configuration key without a default

Full example

A complete Bedrock-style application.php configuration file:

<?php

use Roots\WPConfig\Config;

$rootDir = dirname(__DIR__);
$webrootDir = $rootDir . '/web';

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

$config
    /**
     * DB settings
     */
    ->env(['DB_NAME', 'DB_USER', 'DB_PASSWORD'])
    ->env('DB_HOST', 'localhost')
    ->set([
        'DB_CHARSET' => 'utf8mb4',
        'DB_COLLATE' => '',
    ])
    ->doAction('database_configured')

    /**
     * URLs
     */
    ->env('WP_HOME')
    ->set('WP_SITEURL', $config->get('WP_HOME') . '/wp')
    ->doAction('urls_configured')

    /**
     * Environment
     */
    ->env('WP_ENV', 'production')
    ->set('WP_ENVIRONMENT_TYPE', $config->get('WP_ENV'))
    ->doAction('environment_loaded')

    /**
     * Content directory
     */
    ->set([
        'CONTENT_DIR' => '/app',
        'WP_CONTENT_DIR' => "{$webrootDir}/app",
        'WP_CONTENT_URL' => $config->get('WP_HOME') . '/app',
    ])

    /**
     * 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)
    ->env('DISABLE_WP_CRON', false)
    ->set('DISALLOW_FILE_EDIT', true)
    ->env('DISALLOW_FILE_MODS', true)
    ->env('WP_POST_REVISIONS', true)

    /**
     * Performance settings
     */
    ->set('CONCATENATE_SCRIPTS', false)

    /**
     * Default debug settings
     */
    ->env('WP_DEBUG', false)
    ->set('WP_DEBUG_DISPLAY', false)
    ->set('WP_DEBUG_LOG', false)
    ->set('SCRIPT_DEBUG', false)

    /**
     * Development settings
     */
    ->when($config->get('WP_ENV') === 'development', function ($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_INDEXING' => true,
            'DISALLOW_FILE_MODS' => false,
        ]);
    })

    /**
     * Handle reverse proxy settings
     */
    ->when(
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https',
        function () { $_SERVER['HTTPS'] = 'on'; },
    )

    ->apply();

$config->doAction('after_apply');

$table_prefix = $_ENV['DB_PREFIX'] ?? 'wp_';

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

require_once ABSPATH . 'wp-settings.php';

Community

Keep track of development and community news.

roots/wp-config 适用场景与选型建议

roots/wp-config 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8.04M 次下载、GitHub Stars 达 60, 最近一次更新时间为 2018 年 08 月 07 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 roots/wp-config 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 roots/wp-config 我们能提供哪些服务?
定制开发 / 二次开发

基于 roots/wp-config 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 8.04M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 63
  • 点击次数: 21
  • 依赖项目数: 91
  • 推荐数: 0

GitHub 信息

  • Stars: 60
  • Watchers: 8
  • Forks: 8
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-08-07