允许Symfony 2 Bundle语义配置中的键值对

gre*_*emo 22 bundle dependency-injection symfony

基本上我想在我的配置中允许任意(但不是空)数量的键值对,在billings节点下,定义一个关联数组.

我在我的Configurator.php(部分)中有这个:

->arrayNode('billings')
    ->isRequired()
    ->requiresAtLeastOneElement()
    ->prototype('scalar')
    ->end()
->end()
Run Code Online (Sandbox Code Playgroud)

然后,在我的config.yml:

my_bundle:
    billings:
        monthly : Monthly
        bimonthly : Bimonthly
Run Code Online (Sandbox Code Playgroud)

但是,输出$config:

class MyBundleExtension extends Extension
{
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $loader = new Loader\YamlFileLoader($container,
            new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        $processor     = new Processor();
        $configuration = new Configuration();

        $config = $processor->processConfiguration($configuration, $configs);

        $container->setParameter('my_bundle.billings', $config['billings']);

        var_dump($config);
        die();
    }

}
Run Code Online (Sandbox Code Playgroud)

...我得到的是数字索引,而不是关联索引:

 'billings' => 
     array (size=2)
         0 => string 'Monthly' (length=7)
         1 => string 'Bimonthly' (length=9)
Run Code Online (Sandbox Code Playgroud)

出于好奇(如果这可以帮助),我正在尝试将此数组作为服务参数注入(来自这个伟大的包的注释:JMSDiExtraBundle):

class BillingType extends \Symfony\Component\Form\AbstractType
{

    /**
     * @var array
     */
    private $billingChoices;

    /**
     * @InjectParams({"billingChoices" = @Inject("%billings%")})
     *
     * @param array $billingChoices
     */
    public function __construct(array $billingChoices)
    {
        $this->billingChoices = $billingChoices;
    }
} 
Run Code Online (Sandbox Code Playgroud)

小智 24

您应该添加useAttributeAsKey('name')到您的结算节点配置中Configurator.php.

有关useAttributeAsKey()您的更多信息,请参阅Symfony API文档

更改结算节点配置后应该是:

->arrayNode('billings')
    ->isRequired()
    ->requiresAtLeastOneElement()
    ->useAttributeAsKey('name')
    ->prototype('scalar')->end()
->end()
Run Code Online (Sandbox Code Playgroud)

  • 我更正确的是` - > useAttributeAsKey('name')``name`有特殊含义,或者它至少会自动添加到数组中? (2认同)