config.yml 中的变量 [英] Variables in config.yml

查看:30
本文介绍了config.yml 中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我在 Symfony2/app/config/config.yml 中使用:

If i use in Symfony2 /app/config/config.yml:

parameters:
    test_first: aaaa
    test_second: bbbb

twig:
    globals:
        first: %test_first%

那么这个工作正常

但我想制作:

parameters:
    test:
        first: aaaa
        second: bbbb

twig:
    globals:
        first: %test_first%

我有错误:

ParameterNotFoundException:您请求了一个不存在的参数test_first".

ParameterNotFoundException: You have requested a non-existent parameter "test_first".

我该怎么做?

推荐答案

依赖注入在 Symfony 中是一个冗长的主题,并且有大量关于细节的文档,所以我只在这里给你介绍.

Dependency Injection is a lengthy subject in Symfony and there is plenty of documentation on the details, so I'll just give you the run down here.

parameters.yml 文件应包含平面键/值对.配置文件应该从中读取,参数可以包含数组,但是你不能像这样在 Symfony 中引用 subs.

The parameters.yml file should contain flat key/value pairs. Config files should read from them, it is possible for parameters to contain arrays, however you cannot reference the subs in Symfony like this.

相反,您可以为配置节点提供整个参数数组.这将带您到:http://symfony.com/doc/current/components/config/definition.html

Instead you can give a config node the entire parameter array. Which takes you to: http://symfony.com/doc/current/components/config/definition.html

下一步是更改包的扩展类中的服务容器.http://symfony.com/doc/current/components/dependency_injection/compilation.html#managing-configuration-with-extensions

Next step is to alter the Service Container in the Extension class of your bundle. http://symfony.com/doc/current/components/dependency_injection/compilation.html#managing-configuration-with-extensions

从包含来自 yml 的参数的配置节点读取并创建容器参数的超集.

Read from the config node which contains the parameters from the yml and create a superset of container parameters.

例如:

foreach($config['test'] as $key => $value) {
    $container->setParameter($this->getAlias().'.test.'.$key, $value);
}

这将创建一段参数,例如:

This will create a section of parameters such as:

myapp.test.first  = aaaa
myapp.test.second = bbbb

并从控制器访问:

$value = $this->container->getParameter('myapp.test.first');

但是请注意,bundle 不应真正依赖于 parameters.yml 值的存在,因为如果该参数不存在,则上述语句将抛出错误,除非您先调用 hasParameter.

Be aware however that bundles should not really be dependent on the existence of parameters.yml values, because if that parameter does not exist, the above statement will throw an error, unless you call hasParameter first.

这篇关于config.yml 中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆