您可以通过Extension Classes 在 Symfony 中定义默认配置,也可以看看这个Symfony Bundle Configuration 指南,它解释了很多关于捆绑配置的内容。默认配置可以用于教义、翻译或您可以在应用程序级别配置的任何其他内容。甚至可以使用Prepend Extension修改其他捆绑包配置
Config 组件负责管理此配置规则,您可以从文档中的Config Component 和Defining and Processing Configuration Values 页面了解更多信息。
FOSOAuthServerBundle 是 Doctrine 默认配置的示例。
他们更喜欢 XML,但这是一种格式决定,XML、YAML 或 PHP 的配置逻辑相同。
msgphp/user-bundle 配置是另一个通过 PHP 文件进行配置的示例。
让我们用代码说话,这是一个带有教义实体和简单配置数组的 YAML 配置示例。
首先,创建配置类为我们的包提供默认配置规则。
// src/Acme/HelloBundle/DependencyInjection/Configuration.php
namespace Acme\HelloBundle\DependencyInjection;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
class Configuration implements ConfigurationInterface
{
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('acme_hello');
$rootNode
->children()
->arrayNode('simple_array')
->children()
->scalarNode('foo')->end()
->scalarNode('bar')->end()
->end()
->end()
->arrayNode('doctrine')
->children()
->arrayNode('entity')
->children()
->scalarNode('class')->isRequired()->cannotBeEmpty()->end()
->end()
->end()
->arrayNode('manager')
->children()
->scalarNode('class')->defaultValue('Acme\\HelloBundle\\Entity\\Manager\\EntryManager')->end()
->end()
->end()
->end()
->end()
->end()
;
return $treeBuilder;
}
}
其次,准备我们的包的扩展类以加载此配置。
//src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php
namespace Acme\HelloBundle\DependencyInjection;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
class AcmeHelloExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__.'/../Resources/config')
);
$loader->load('acme_hello.yaml');
$loader->load('services.yaml');
// you now have these 2 config keys
// $config['simple_array'] and $config['doctrine']
// $container->getDefinition('acme_hello.simple_array.foo');
}
}
最后,创建默认 YAML 定义并将我们的条目管理器注册到容器。
//src/Acme/HelloBundle/Resources/config/acme_hello.yaml
acme_hello:
simple_array:
foo: 'hello'
bar: 'world'
doctrine:
entity:
class: 'Acme\HelloBundle\Entity\Entry'
manager:
class: 'Acme\HelloBundle\Entity\Manager\EntryManager'
//src/Acme/HelloBundle/Resources/config/services.yaml
services:
acme_hello.entry_manager:
class: '%acme_hello.doctrine.manager.class%'
arguments: [ '@doctrine.orm.entity_manager', '%acme_hello.doctrine.entity.class%' ]
我们还可以在应用程序级别覆盖默认配置。
//config/packages/acme_hello.yaml
acme_hello:
simple_array:
foo: 'world'
bar: 'hello'