如何简化多个bundle的配置

编辑本页

警告:您正在浏览的文档欧宝官网下载appob娱乐下载Symfony 2.7,现已不再维护。

本页的更新版本用于Syob娱乐下载mfony 6.2(当前稳定版本)。

如何简化多个bundle的配置

在构建可重用和可扩展的应用程序时,开发人员经常面临一个选择:创建一个大型捆绑包或多个较小的捆绑包。创建单个包的缺点是用户不可能选择删除他们不使用的功能。创建多个捆绑包的缺点是,配置变得更加繁琐,并且经常需要为各种捆绑包重复设置。

通过启用单个扩展来预先设置任何包,可以消除多包方法的缺点。方法中定义的设置应用程序/配置/ config.yml预先结束设置,就好像它们是由用户在应用程序配置中显式编写的一样。

例如,这可以用于配置实体管理器名称,以便在多个捆绑包中使用。或者也可以使用它来启用依赖于正在加载的另一个bundle的可选特性。

为了给扩展提供这样做的能力,它需要实现PrependExtensionInterface

12 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/ / src / Acme / HelloBundle / DependencyInjection / AcmeHelloExtension.php名称空间AcmeHelloBundleDependencyInjection使用ob娱乐下载组件HttpKernelDependencyInjection扩展使用ob娱乐下载组件DependencyInjection扩展PrependExtensionInterface使用ob娱乐下载组件DependencyInjectionContainerBuilderAcmeHelloExtension扩展扩展实现了PrependExtensionInterface/ /……公共函数预谋(ContainerBuilder容器/ /……}}

预先考虑()方法,开发人员可以完全访问ContainerBuilder实例。load ()方法在每个注册的bundle Extensions上被调用。为了将设置前置到包扩展,开发人员可以使用prependExtensionConfig ()方法。ContainerBuilder实例。类中显式完成的任何其他设置,由于此方法仅作为设置的前缀应用程序/配置/ config.yml将覆盖这些前置设置。

下面的例子说明了如何在多个bundle中预先设置一个配置,以及在多个bundle中禁用一个标志,以防特定的其他bundle未注册:

12 34 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
/ / src / Acme / HelloBundle / DependencyInjection / AcmeHelloExtension.php公共函数预谋(ContainerBuilder容器//获取所有bundle容器->getParameter (“kernel.bundles”);//确定是否注册了acme好孩子bundle如果(!收取“AcmeGoodbyeBundle”))) {//在bundle中禁用acme好孩子bundle配置数组“use_acme_goodbye”= >);foreach容器->getExtensions ()作为的名字= >扩展){开关的名字){情况下“acme_something”情况下“acme_other”//在config中将use_acme_goodbye设置为false// acme_something和acme_other////注意如果用户手动配置// use_acme_goodbye在app/config/config.yml中设置为true//那么该设置最终将为真而不是假容器->prependExtensionConfig (的名字配置);打破;}}}//处理AcmeHelloExtension的配置配置容器->getExtensionConfig (->getAlias ());//使用Configuration类生成一个配置数组//设置"acme_hello"配置->processConfiguration (配置(),配置);//检查“acme_hello”配置中是否设置了entity_manager_name如果收取配置“entity_manager_name”))) {//在acme_something设置前加上entity_manager_name配置数组“entity_manager_name”= >配置“entity_manager_name”]);容器->prependExtensionConfig (“acme_something”配置);}}

上面的内容相当于将下面的内容写入应用程序/配置/ config.yml如果acme好孩子bundle没有注册entity_manager_name设置acme_hello设置为non_default

  • YAML
  • XML
  • PHP
1 2 3 4 5 6 7 8 9
# app / config / config.ymlacme_something:#……use_acme_goodbye:entity_manager_name:non_defaultacme_other:#……use_acme_goodbye:

使用PrependExtensionInterface的多个Bundle

如果有多个bundle前缀相同的扩展名并定义了相同的键,则注册的是该bundle第一个优先级:next bundles不会覆盖这个特定的配置设置。

此工作,包括代码示例,是根据创作共用BY-SA 3.0许可证。