[英]Symfony: How to load custom bundle config from file?
我正在使用Symfony 3.4
。 如何将自定义配置文件添加到应包含名称和正则表达式列表的自定义包中? 例如:
// Config file content = list of names and regular expressions
NameA
NameB
Name[cC]+
Some\w+Other(Name|Pattern)
...
// Symfony controller
$patterns = $this->getPatternConfigFromFileSomehow(...);
在Symfony文档中,我找到了有关在app/config
或MyBundle/Resources/config
目录.yml
自定义配置添加到.yml
文件的信息。 但是,这不是一mailaddress: xyz
定义良好的参数(例如mailaddress: xyz
),而是任何数量的条目的列表。
另外,仅当配置实际使用时才应加载配置,而不是每次创建内核或服务时才加载。
当然,我可以简单地使用file_get_contents
或任何类似的PHP方法来加载任何文件,但是这似乎很hacky,而不是“ Symfony方式” ...
那么,这样做的“正确”方法是什么?
编辑:
yml文件非常适合配置参数 ,但这与参数(=键+值) 无关 ,而是文件名和正则表达式的列表。 这份名单没有确定的长度和条目没有定义的名称。 因此,.yml在这里不是正确的解决方案,对吗?
另外,使用ConfigTreeBuilder添加的配置文件是在加载内核时加载的,不是吗? 我正在寻找一种仅在需要时才加载列表的惰性解决方案。
将您的yml文件放入已加载的任何配置目录(app / config,config,Resources / config)中。 您如何命名文件并不重要。 重要的是,此yml中的根节点是您在/your-bundle/src/DependencyInjection/Configuration.php中定义的根节点
如果您这样定义它:
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder('your_root_node' );
$treeBuilder->getRootNode()...
// with use of array prototypes...
$treeBuilder = new TreeBuilder('your_root_node');
$rootNode = $treeBuilder->getRootNode();
$rootNode
->children()
->arrayNode('fields')
->arrayPrototype()
->children()
->enumNode('type')
->values(['iris','iri','entity','entities','datetime','string','integer','boolean','custom_class'])
->defaultNull()
->end()
->enumNode('type_out')
->values(['iris','iri','entity','entities','datetime','string','integer','boolean','custom_class'])
->defaultNull()
->end()
->scalarNode('entity')->defaultNull()->end()
->scalarNode('customClass')->defaultNull()->end()
->arrayNode('parameters')
->useAttributeAsKey('name')
->scalarPrototype()->end()
->end()
->booleanNode('nullable')->defaultFalse()->end()
->end()
->end()
->end()
->end()
;
...
}
然后,您应该有一个像这样开始的yml文件:
your_root_node:
my_parameter:
my_other_parameter:
and_so_on:
同样,具有定义的配置文件也不必加载内核,并且可以“懒惰”地加载到这样的服务中:
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
use Symfony\Component\Config\Definition\Processor;
class SchemaConfiguration implements ConfigurationInterface
{
/**
* {@inheritdoc}
*/
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('schema');
$rootNode
... // Tree definition
->end()
;
return $treeBuilder;
}
/**
* @param $schemaConfig
* @return mixed
*/
public function getSchemaFromYaml($schemaConfig){
$configuration = new SchemaConfiguration();
$processor = new Processor();
$processed = $processor->processConfiguration($configuration, $schemaConfig);
$schema = $processed['fields'];
return $schema ;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.