###1.建立一個自動加載的擴展類 *. 類在DependencyInjection命令空間下(一般文件位置位於DependencyInjection 目錄下) *. 文件的命令是去掉Bundle的名稱的後綴Bundle用Extension來替代(eg AppBundle --> AppExtesion)php
該類須要實現ExtensionInterface接口;一般經過繼承 Extension類來實現ui
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.php namespace Acme\HelloBundle\DependencyInjection; use Symfony\Component\HttpKernel\DependencyInjection\Extension; use Symfony\Component\DependencyInjection\ContainerBuilder; class AcmeHelloExtension extends Extension { public function load(array $configs, ContainerBuilder $container) { // ... you'll load the files here later } }
###2. 手動註冊一個擴展類 若是咱們不遵照上面自動加載的約束;咱們將要手動註冊該擴展類;咱們須要重寫Bundle的getContainerExtension方法;該方法返回咱們的擴展類的實例spa
use Acme\HelloBundle\DependencyInjection\UnconventionalExtensionClass; class AcmeHelloBundle extends Bundle { public function getContainerExtension() { return new CustomerExtension();//自定義的擴展類 } }
自定義的擴展類;須要重寫getAlias方法返回DI的別名;一般就是去掉Extension後綴的(eg AcmeHelloExtension-->acme_hello) class CustomerExtension extends Extension { /** * {@inheritdoc} * load方法全部和extension相關的配置,服務將要被加載 * */ public function load(array $configs, ContainerBuilder $container) { //有 YamlFileLoader, PhpFileLoader,IniFileLoader. $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yml'); } public function getAlias() { return 'acme_hello'; } }