Symfony 如何像参数一样直接在容器中获取捆绑包的配置
我创建了一个包来加载我的自定义配置文件。 我的配置文件如下所示,名为cronjob_properties.yaml:Symfony 如何像参数一样直接在容器中获取捆绑包的配置,symfony,Symfony,我创建了一个包来加载我的自定义配置文件。 我的配置文件如下所示,名为cronjob_properties.yaml: cronjob_properties: task: name: 'all_items' 我在名为PropertiesBundle的包中加载的扩展如下所示 class CronjobPropertiesExtension extends Extension implements PrependExtensionInterface { public
cronjob_properties:
task:
name: 'all_items'
我在名为PropertiesBundle的包中加载的扩展如下所示
class CronjobPropertiesExtension extends Extension implements PrependExtensionInterface
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new CronjobPropertiesConfiguration();
$config = $this->processConfiguration($configuration, $configs);
}
}
我的配置文件已正确解析。
然后我有一个配置树生成器来验证配置文件
class CronjobPropertiesConfiguration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('cronjob_properties');
$treeBuilder->getRootNode()
->children()
->arrayNode('task')
->children()
->scalarNode('name')->end()
->end()
->end() //task
->end();
return $treeBuilder;
}
现在我想在我的应用程序中使用配置。
到目前为止,我尝试的是直接从ContainerInterface读取配置文件
像这样
class CronjobPropertiesExtension extends Extension implements PrependExtensionInterface
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new CronjobPropertiesConfiguration();
$config = $this->processConfiguration($configuration, $configs);
}
}
$this->container['cronjob_properties']
但这不起作用。
我在文档中发现,我需要手动解析Yaml文件,然后调用processConfiguration。
是否有更简单的方法从控制器或项目中的任何其他类访问我的配置文件?在扩展类中的load方法中,设置参数:
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new CronjobPropertiesConfiguration();
$config = $this->processConfiguration($configuration, $configs);
$container->setParameter('foobar', $config['foobar']);
}
在扩展中,您可以设置处理配置时所需的参数。无法直接从应用程序的其他部分读取配置。认为各种配置文件的内容可以通过容器自动访问是一个常见的错误。正如其他一些人所提到的那样,它根本不起作用。您可以考虑创建某种CRONJOBMAMER类,然后使用配置属性初始化扩展中的服务。这将使您不再直接在应用程序代码中使用参数。这基本上就是大多数捆绑包的功能。@claudio ferraro如果回答了您的问题,请将此标记为答案。如果没有,请告诉我,我会尽力帮助你。