Skip to content

Commit 95e2534

Browse files
lonnieezellclaude
andauthored
perf: scan the environment once when building config classes (#10657)
* perf(#10615): scan the environment once when building config classes `BaseConfig::__construct()` checked every leaf property against `$_ENV`, `$_SERVER` and four `getenv()` calls, so the common no-override path was also the slowest. The environment is now indexed once, grouped by the text before the first "." or "_", and each class only walks the keys that match its prefixes. The index is rebuilt when `$_ENV` or `$_SERVER` changes (once per request in Worker Mode) or on `BaseConfig::reset()`. PHP's `getenv()` array omits names containing ".", " " or "[", so those are looked up with `getenv()` on each class's first build and cached for the process. Classes that override `getEnvValue()` or `initEnvValue()` keep the previous live lookups. Lookup precedence is unchanged. Building 20 core config classes (PHP 8.3 CLI, no opcache, median): | Scenario | Before | After | |---------------------------------------|----------|----------| | Warm, no overrides, new $_SERVER | 0.456 ms | 0.073 ms | | Warm, no overrides, unchanged env | 0.456 ms | 0.031 ms | | Warm, 5 overrides, new $_SERVER | 0.467 ms | 0.110 ms | | Warm, 5 overrides, unchanged env | 0.471 ms | 0.067 ms | | Cold first build, no overrides | 0.493 ms | 0.205 ms | | Cold first build, 5 overrides | 0.505 ms | 0.267 ms | Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(#10615): re-read live env vars on every config build Cache only the names of env vars found with live getenv() calls, per leaf, and re-read their values on each build, so removed or changed values are not reused. Leaves first seen on a later instance are now probed too. On Windows, probe the underscore forms live as well, so they keep matching case-insensitively. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(#10615): probe underscore env names live under Apache mod_php Under Apache mod_php, live getenv() reads SetEnv vars case-insensitively, so `SetEnv APP_BASEURL` matched `app_baseURL` in 4.8, but the indexed $_SERVER and getenv() array only hold the exact name. Probe the underscore forms live on any SAPI not known to match names exactly, keeping the cheaper path for CLI, FPM and FrankenPHP. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * docs(#10615): clarify putenv() cache limits in Worker Mode Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 58efb74 commit 95e2534

8 files changed

Lines changed: 586 additions & 47 deletions

File tree

‎system/Config/BaseConfig.php‎

Lines changed: 292 additions & 47 deletions
Large diffs are not rendered by default.

‎tests/system/Config/BaseConfigTest.php‎

Lines changed: 159 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,20 @@
1818
use CodeIgniter\Superglobals;
1919
use CodeIgniter\Test\CIUnitTestCase;
2020
use Config\Modules;
21+
use CustomEnvHookConfig;
2122
use Encryption;
23+
use EnvIndexConfig;
24+
use GrowingEnvConfig;
2225
use MergeRegistrarConfig;
26+
use PHPUnit\Framework\Attributes\DataProvider;
2327
use PHPUnit\Framework\Attributes\Group;
2428
use PHPUnit\Framework\Attributes\PreserveGlobalState;
2529
use PHPUnit\Framework\Attributes\RunInSeparateProcess;
2630
use PHPUnit\Framework\Attributes\WithoutErrorHandler;
2731
use PHPUnit\Framework\MockObject\MockObject;
2832
use RegistrarConfig;
2933
use SimpleConfig;
34+
use Snake_Config;
3035
use Tests\Support\Config\BadRegistrar;
3136
use Tests\Support\Config\MergeOrderRegistrar;
3237
use Tests\Support\Config\MergePlainRegistrar;
@@ -67,6 +72,12 @@ protected function setUp(): void
6772
require $this->fixturesFolder . '/Encryption.php';
6873
}
6974

75+
foreach (['EnvIndexConfig', 'Snake_Config', 'CustomEnvHookConfig', 'GrowingEnvConfig'] as $class) {
76+
if (! class_exists($class, false)) {
77+
require $this->fixturesFolder . '/' . $class . '.php';
78+
}
79+
}
80+
7081
BaseConfig::reset();
7182

7283
Services::injectMock('superglobals', new Superglobals());
@@ -77,6 +88,7 @@ protected function tearDown(): void
7788
parent::tearDown();
7889

7990
$this->clearEnvironmentOverrides();
91+
GrowingEnvConfig::$grow = false;
8092
// This test modifies BaseConfig::$modules, so should reset.
8193
BaseConfig::reset();
8294
// This test modifies Services locator, so should reset.
@@ -93,6 +105,16 @@ private function clearEnvironmentOverrides(): void
93105
'SimpleConfig.QZEROSTR',
94106
'SimpleConfig.QEMPTYSTR',
95107
'SimpleConfig.QFALSE',
108+
'envindexconfig.name',
109+
'envindexconfig_name',
110+
'EnvIndexConfig.name',
111+
'envindexconfig.list.key',
112+
'envindexconfig.list.missing',
113+
'envindexconfig_list_some key',
114+
'snake_config.name',
115+
'Snake_Config_name',
116+
'customenvhookconfig.name',
117+
'growingenvconfig.list.added',
96118
] as $key) {
97119
putenv($key);
98120
unset($_ENV[$key]);
@@ -425,4 +447,141 @@ public function testRedoingDiscoveryWillStillSetDidDiscoveryPropertyToTrue(): vo
425447

426448
$this->assertTrue($this->getPrivateProperty($config, 'didDiscovery'));
427449
}
450+
451+
public function testEnvWritesAfterConstructionArePickedUp(): void
452+
{
453+
$this->assertSame('default', (new EnvIndexConfig())->name);
454+
455+
$_ENV['envindexconfig.name'] = 'from-env';
456+
$this->assertSame('from-env', (new EnvIndexConfig())->name);
457+
458+
unset($_ENV['envindexconfig.name']);
459+
service('superglobals')->setServer('envindexconfig.name', 'from-server');
460+
$this->assertSame('from-server', (new EnvIndexConfig())->name);
461+
}
462+
463+
public function testResetPicksUpBarePutenv(): void
464+
{
465+
$this->assertSame('default', (new EnvIndexConfig())->name);
466+
467+
putenv('envindexconfig.name=from-getenv');
468+
BaseConfig::reset();
469+
470+
$this->assertSame('from-getenv', (new EnvIndexConfig())->name);
471+
}
472+
473+
public function testOverriddenEnvHookIsCalledAndReadsLiveGetenv(): void
474+
{
475+
$config = new CustomEnvHookConfig();
476+
477+
$this->assertSame('from-hook', $config->hooked);
478+
$this->assertSame('default', $config->name);
479+
480+
putenv('customenvhookconfig.name=live');
481+
482+
$this->assertSame('live', (new CustomEnvHookConfig())->name);
483+
}
484+
485+
public function testShortPrefixWithUnderscore(): void
486+
{
487+
$_ENV['snake_config.name'] = 'short';
488+
$this->assertSame('short', (new Snake_Config())->name);
489+
490+
unset($_ENV['snake_config.name']);
491+
$_ENV['Snake_Config_name'] = 'full';
492+
$this->assertSame('full', (new Snake_Config())->name);
493+
}
494+
495+
/**
496+
* @param array<string, string> $env
497+
* @param array<string, string> $server
498+
* @param array<string, string> $getenv
499+
*/
500+
#[DataProvider('provideEnvPrecedence')]
501+
public function testEnvPrecedence(array $env, array $server, array $getenv, string $expected): void
502+
{
503+
foreach ($env as $key => $value) {
504+
$_ENV[$key] = $value;
505+
}
506+
507+
foreach ($server as $key => $value) {
508+
service('superglobals')->setServer($key, $value);
509+
}
510+
511+
foreach ($getenv as $key => $value) {
512+
putenv("{$key}={$value}");
513+
}
514+
515+
$this->assertSame($expected, (new EnvIndexConfig())->name);
516+
}
517+
518+
/**
519+
* @return iterable<string, array{array<string, string>, array<string, string>, array<string, string>, string}>
520+
*/
521+
public static function provideEnvPrecedence(): iterable
522+
{
523+
yield 'short prefix in $_SERVER beats full prefix in $_ENV' => [
524+
['EnvIndexConfig.name' => 'full'], ['envindexconfig.name' => 'short'], [], 'short',
525+
];
526+
527+
yield '$_ENV beats $_SERVER' => [
528+
['envindexconfig.name' => 'env'], ['envindexconfig.name' => 'server'], [], 'env',
529+
];
530+
531+
yield '$_SERVER beats getenv()' => [
532+
[], ['envindexconfig.name' => 'server'], ['envindexconfig.name' => 'getenv'], 'server',
533+
];
534+
535+
yield 'full prefix in $_ENV beats short prefix in getenv()' => [
536+
['EnvIndexConfig.name' => 'full'], [], ['envindexconfig.name' => 'getenv'], 'full',
537+
];
538+
539+
yield 'dot form beats underscore form' => [
540+
['envindexconfig_name' => 'underscore', 'envindexconfig.name' => 'dot'], [], [], 'dot',
541+
];
542+
543+
yield 'getenv() only' => [
544+
[], [], ['envindexconfig.name' => 'getenv'], 'getenv',
545+
];
546+
}
547+
548+
public function testArrayOverridesOnlyApplyToExistingKeys(): void
549+
{
550+
$_ENV['envindexconfig.list.key'] = 'overridden';
551+
$_ENV['envindexconfig.list.missing'] = 'ignored';
552+
553+
$this->assertSame(['key' => 'overridden', 'some key' => 'default'], (new EnvIndexConfig())->list);
554+
}
555+
556+
public function testGetenvOnlyNameWithSpace(): void
557+
{
558+
// The getenv() array omits names with a space, like names with a dot.
559+
putenv('envindexconfig_list_some key=from-getenv');
560+
561+
$this->assertSame('from-getenv', (new EnvIndexConfig())->list['some key']);
562+
}
563+
564+
public function testRemovedGetenvOnlyNameIsNotReused(): void
565+
{
566+
putenv('envindexconfig.name=old');
567+
$_ENV['envindexconfig.name'] = 'old';
568+
service('superglobals')->setServer('envindexconfig.name', 'old');
569+
$this->assertSame('old', (new EnvIndexConfig())->name);
570+
571+
putenv('envindexconfig.name');
572+
unset($_ENV['envindexconfig.name']);
573+
service('superglobals')->unsetServer('envindexconfig.name');
574+
575+
$this->assertSame('default', (new EnvIndexConfig())->name);
576+
}
577+
578+
public function testGetenvOnlyNameForLeafAddedOnLaterInstance(): void
579+
{
580+
putenv('growingenvconfig.list.added=from-getenv');
581+
$this->assertSame(['key' => 'default'], (new GrowingEnvConfig())->list);
582+
583+
GrowingEnvConfig::$grow = true;
584+
585+
$this->assertSame(['key' => 'default', 'added' => 'from-getenv'], (new GrowingEnvConfig())->list);
586+
}
428587
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
use CodeIgniter\Config\BaseConfig;
15+
16+
class CustomEnvHookConfig extends BaseConfig
17+
{
18+
public string $name = 'default';
19+
public string $hooked = 'default';
20+
21+
protected function getEnvValue(string $property, string $prefix, string $shortPrefix)
22+
{
23+
if ($property === 'hooked') {
24+
return 'from-hook';
25+
}
26+
27+
return parent::getEnvValue($property, $prefix, $shortPrefix);
28+
}
29+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
use CodeIgniter\Config\BaseConfig;
15+
16+
class EnvIndexConfig extends BaseConfig
17+
{
18+
public string $name = 'default';
19+
20+
/**
21+
* @var array<string, string>
22+
*/
23+
public array $list = [
24+
'key' => 'default',
25+
'some key' => 'default',
26+
];
27+
}
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
use CodeIgniter\Config\BaseConfig;
15+
16+
/**
17+
* Adds an array leaf only when $grow is set, like a constructor or registrar
18+
* that changes the shape between instances.
19+
*/
20+
class GrowingEnvConfig extends BaseConfig
21+
{
22+
public static bool $grow = false;
23+
24+
/**
25+
* @var array<string, string>
26+
*/
27+
public array $list = ['key' => 'default'];
28+
29+
public function __construct()
30+
{
31+
if (self::$grow) {
32+
$this->list['added'] = 'default';
33+
}
34+
35+
parent::__construct();
36+
}
37+
}
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
use CodeIgniter\Config\BaseConfig;
15+
16+
class Snake_Config extends BaseConfig
17+
{
18+
public string $name = 'default';
19+
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,9 @@ Behavior Changes
6969
- **Commands:** The ``worker:uninstall`` command now returns ``EXIT_SUCCESS`` (previously ``EXIT_ERROR``) when the user declines the interactive confirmation prompt, since user-initiated cancellation is not a failure. In non-interactive mode without ``--force`` it now aborts with ``EXIT_ERROR`` instead of prompting, and the redundant ``Uninstalling FrankenPHP Worker Mode`` header was dropped. Scripts that branch on the previous exit code or wording will need updating.
7070
- **Commands:** The ``phpini:check`` command's invalid-argument error now prints only ``You must specify a correct argument.``. The usage example and the argument listing moved to ``phpini:check --help``, where the argument is now named ``section``. Scripts that grep the previous output will need updating.
7171
- **Config:** ``CodeIgniter\Config\BaseService`` is now ``abstract``. It is intended to be extended (as ``Config\Services`` does) and accessed statically; code that instantiated it directly with ``new BaseService()`` will now throw an ``Error``.
72+
- **Config:** ``BaseConfig`` now scans the environment once instead of checking every property against it, which makes building config classes
73+
several times faster without config caching and in Worker Mode. As a result, a bare ``putenv()`` call (adding, changing, or removing a variable) made
74+
after the first config class was built may not be seen until ``BaseConfig::reset()`` runs, including in later requests in Worker Mode. See :ref:`upgrade-480-config-env-lookups`.
7275
- **Database:** The Postgre driver's ``$db->error()['code']`` previously always returned ``''``. It now returns the 5-character SQLSTATE string for query and transaction failures (e.g., ``'42P01'``), or ``'08006'`` for connection-level failures. Code that relied on ``$db->error()['code'] === ''`` will need updating.
7376
- **Debug:** ``CodeIgniter\Debug\Toolbar\Collectors\BaseCollector`` is now ``abstract``. Custom toolbar collectors must extend it; code that instantiated it directly with ``new BaseCollector()`` will now throw an ``Error``.
7477
- **Filters:** HTTP method matching for method-based filters is now case-sensitive. The keys in ``Config\Filters::$methods`` must exactly match the request method

‎user_guide_src/source/installation/upgrade_480.rst‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,26 @@ RedirectException Default Status Code
175175
protected int $defaultStatusCode = 307;
176176
}
177177
178+
.. _upgrade-480-config-env-lookups:
179+
180+
Config Environment Lookups
181+
==========================
182+
183+
``BaseConfig`` now reads the environment once and reuses the result, instead of
184+
looking up every property of every config class. The matching rules and their
185+
order are unchanged. One edge case behaves differently: a ``putenv()`` call
186+
that does not also write ``$_ENV`` or ``$_SERVER``, made after the first config
187+
class was built, may not be seen by config classes built later until
188+
``BaseConfig::reset()`` runs. This applies whether the variable is added,
189+
changed, or removed. In Worker Mode, this cache persists across requests, so
190+
such changes may not be seen in later requests either. To make the change
191+
visible, also set the value in ``$_ENV`` (or unset it there), or call
192+
``BaseConfig::reset()``. Values loaded from the **.env** file are not
193+
affected, since they are written to ``$_ENV`` and ``$_SERVER`` as well.
194+
195+
Config classes that override ``getEnvValue()`` or ``initEnvValue()`` keep the
196+
previous behavior.
197+
178198
RouteCollection Identifier Transformation
179199
=========================================
180200

0 commit comments

Comments
 (0)