###1.创建一个自动加载的扩展类 *. 类在DependencyInjection命令空间下(通常文件位置位于DependencyInjection 目录下) *. 文件的命令是去掉Bundle的名称的后缀Bundle用Extension来替代(eg AppBundle --> AppExtesion)
该类需要实现ExtensionInterface接口;通常通过继承 Extension类来实现
// src/Acme/HelloBundle/DependencyInjection/AcmeHelloExtension.phpnamespace 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方法;该方法返回我们的扩展类的实例
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'; }}