Yii2 覆盖嵌套配置参数

Yii2 override nested config parameters

我以这种方式合并我的配置:

$config = \yii\helpers\ArrayHelper::merge(
    (require (__DIR__ . '/../config/web.php')),
    (require __DIR__ . '/../config/overrides/web.php')
);

这里是config/web.php

$config = [
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [
                [
                    'class' => 'yii\log\FileTarget',
                    'levels' => ['error', 'warning'],
                ],
                [
                    'class' => 'yii\log\EmailTarget',
                    'levels' => ['info'],
                    'categories' => ['parsingFailure'],
                    'logVars' => [],
                    'message' => [
                        'from' => ['system@host.com'],
                        'to' => ['support@host.com'],
                        'subject' => 'Message parsing failure',
                    ],
                ],
            ],
        ],
        //....some more components
    ]
];

这是我尝试应用的覆盖 config/overrides/web.php

$config = [
    'components' => [
        'log' => [
            'traceLevel' => YII_DEBUG ? 3 : 0,
            'targets' => [],
        ],
    ]
];

所以,我的目标是在本地配置中禁用日志记录。 当然它不起作用,因为 array_merge 的行为不同并且没有任何内容被覆盖。

如果你想让 ArrayHelper 覆盖某些东西,它不能在两个数组中都是一个数组。例如,您可以将 'targets' => [] 更改为 'targets' => null

来自docs

Recursive merging will be conducted if both arrays have an element of array type and are having the same key. [...] You can use yii\helpers\UnsetArrayValue object to unset value from previous array or yii\helpers\ReplaceArrayValue to force replace former value instead of recursive merging.

所以你的第二个数组应该是

'targets' =>  new \yii\helpers\ReplaceArrayValue([]),