Symfony Bundle修改packages下YAML配置后值不更新问题
问题原因分析
核心问题
你遇到的问题根源是:每次Symfony编译容器(执行cache:clear、运行控制台命令等场景)时,你的EntityTablesExtension::load方法都会执行file_put_contents($yamlFilePath, $yaml);,直接覆盖用户修改后的config/packages/entity_tables.yaml文件。
因为processConfiguration方法在用户未修改配置时,会返回Configuration类中定义的默认值(£),所以每次容器编译都会把用户修改后的配置重置为默认值,导致你看不到修改效果。
修复方案
1. 避免每次覆盖用户配置
修改EntityTablesExtension::load方法,仅在配置文件不存在时才初始化写入默认配置,不要每次都覆盖:
public function load(array $configs, ContainerBuilder $container): void { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); $yamlFilePath = $container->getParameter('kernel.project_dir') . '/config/packages/entity_tables.yaml'; // 仅当文件不存在时才创建默认配置,防止覆盖用户修改 if (!file_exists($yamlFilePath)) { $yamlConfig = [ 'entity_tables' => $config, ]; $yaml = Yaml::dump($yamlConfig, 4); file_put_contents($yamlFilePath, $yaml); } // 直接从合并后的配置设置参数(用户配置或默认值) $container->setParameter('entity_tables.currency', $config['currency']); $this->modifyTwigConfiguration($container); }
2. 移除硬编码的默认参数
删除entity-tables-bundle/src/Resources/config/entity_tables.yaml中的硬编码参数定义,因为现在参数值会从合并后的用户配置/默认值中动态获取:
# 原文件内容(删除) parameters: entity_tables.currency: '£'
3. 规范Twig配置(可选但推荐)
不要手动修改项目的twig.yaml,改用Bundle扩展的方式自动合并Twig配置:
- 在你的Bundle主类中添加配置加载逻辑:
// entity-tables-bundle/src/EntityTablesBundle.php use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\Loader\YamlFileLoader; use Symfony\Component\Config\FileLocator; class EntityTablesBundle extends Bundle { public function loadExtension(ContainerBuilder $container): void { $loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/Resources/config')); $loader->load('twig_config.yaml'); } }
- 创建
entity-tables-bundle/src/Resources/config/twig_config.yaml:
twig: paths: '%kernel.project_dir%/vendor/dannyxcii/entity-tables-bundle/src/Resources/views': EntityTables globals: entity_tables_currency: '%entity_tables.currency%'
- 删除
modifyTwigConfiguration方法,不再手动修改用户的twig.yaml文件。
验证修复效果
- 修改
config/packages/entity_tables.yaml中的currency值为$ - 执行
bin/console cache:clear - 运行
bin/console debug:container --parameters | grep entity_tables.currency,此时参数值应显示为$
内容的提问来源于stack exchange,提问作者DannyXCII
相关产品推荐
相关产品推荐

