Symfony 3.4 Hautelook AliceBundle fixtures如何将<current()>传入模板
核心逻辑
你使用的Hautelook AliceBundle核心依赖的Alice库,对<current()> 占位符的求值规则是:该函数永远绑定到当前正在被实例化的具体实体,而非定义模板的实体本身。这意味着完全不需要额外做上下文传值的操作,只需要把公共的关联配置上移到基础模板中,模板里的动态占位符会在每个子实例生成时,自动读取当前实例的序号完成引用匹配。
核心改造步骤
1. 抽离Product实体的重复配置
把原来在每个product_teeth_*下重复书写的两行关联配置,直接移动到template_product模板的定义中。同时可以把分散书写的6个独立产品条目,合并为范围生成的写法,进一步精简冗余代码:
AppBundle\Entity\Product: template_product (template): unit: !php/const AppBundle\Entity\ItemInterface::UNIT_PCS # 公共关联配置,自动适配每个生成实例的序号 categoryProducts: ["@category_product_<current()>_1", "@category_product_<current()>_2"] storeItems: ["@store_product_<current()>_1", "@store_product_<current()>_2"] # 合并原分散的6个产品配置为范围生成,仅保留差异化字段 product_teeth_{1..6} (extends template_product): name: 1: 'Răng sứ kim loại Mỹ ( BH 3 năm )' 2: 'Răng sứ Vita Đức ( BH 4 năm )' 3: 'Răng toàn sứ Zirconia ( CAD/CAM ) ( BH 7 năm )' 4: 'Răng sứ Titan ( BH 5 năm )' 5: 'Răng toàn sứ Full Zirconia ( CAD/CAM ) ( BH 10 năm )' 6: 'Răng toàn sứ Lava Plus - Ceramay (BH 20 năm)' price: 1: 1500000 2: 1800000 3: 3900000 4: 2400000 5: 4400000 6: 1200000
如果你暂时不想把独立条目合并为范围生成的写法,依然可以直接把两行公共关联配置移动到
template_product中,每个产品条目只保留差异化的name、price字段即可,不会影响<current()>的正确取值。
2. 对齐关联实体的生成范围
原配置中CategoryProduct和StoreProduct仅生成了1-3号对应的关联实体,但Product实体共生成了1-6号,会导致4-6号产品的关联引用找不到匹配实体。需要把这两个实体的生成范围从{1..3}调整为{1..6},和产品数量保持对齐:
AppBundle\Entity\CategoryProduct: template_category_product (template): id: <(substr(md5(uniqid(rand(), true)), 0, 18))> template_category_1 (template, extends template_category_product): category: "@category_product" template_category_2 (template, extends template_category_product): category: "@category_product_1" # 调整范围至1..6 category_product_{1..6}_1 (extends template_category_1): item: "@product_teeth_<current()>" category_product_{1..6}_2 (extends template_category_2): item: "@product_teeth_<current()>" AppBundle\Entity\StoreProduct: template_store_product (template): id: <(substr(md5(uniqid(rand(), true)), 0, 18))> template_store_1 (template, extends template_store_product): store: "@store_dentist_1" template_store_2 (template, extends template_store_product): store: "@store_dentist_2" # 调整范围至1..6 store_product_{1..6}_1 (extends template_store_1): item: "@product_teeth_<current()>" store_product_{1..6}_2 (extends template_store_2): item: "@product_teeth_<current()>"
后续扩展说明
如果后续部分产品需要自定义关联规则,只需要在对应产品的配置中覆盖categoryProducts或storeItems字段即可,不会影响其他产品的默认公共逻辑,完全满足DRY的编写要求。
注意:不要在模板定义中硬写固定序号做关联,否则所有扩展该模板的实例都会引用同一个实体,这也是之前容易误以为模板中
<current()>不生效的常见误区。
内容的提问来源于stack exchange,提问作者Ryuk Lee

