代码之家  ›  专栏  ›  技术社区  ›  famas23

寄存器依赖注入(DI)扩展

  •  0
  • famas23  · 技术社区  · 8 年前

    为了自动检测 DI扩展 ,我试图跟随 documentation ,但在我的项目中,我没有在文件夹前面加上 Bundle 我想我需要手动注册分机。

    这是我刚创建的树文件夹结构 AppContextExtension

    portal/src/Common └── Infrastructure └── Symfony ├── Controller └── DependencyInjection └── AppContextExtension

    namespace Portal\Common\Infrastructure\Symfony\DependencyInjection;
    
    use Symfony\Component\HttpKernel\Config\FileLocator;
    use Symfony\Component\HttpKernel\DependencyInjection\Extension;
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\Routing\Loader\YamlFileLoader;
    
    class AppContextExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
           dump('it work');die;
        }
    }
    

    所以你知道如何把这个扩展注册到容器中 dump 活着?为什么分机没有 自动注册 !!!!

    2 回复  |  直到 8 年前
        1
  •  2
  •   Cerad    8 年前

    我想我们是在这里闲逛到拉腊岛的,但我也许这就是你要的例子。

    # portal/src/Symfony 
    # could have been portal/src/Portal/Common/Infrastructure/Symfony
    # but I got lazy
    namespace Portal\Common\Infrastructure\Symfony;
    
    use Portal\Common\Infrastructure\Symfony\DependencyInjection\AppContextExtension;
    use Symfony\Component\HttpKernel\Bundle\Bundle;
    
    # I suppose SymfonyBundle might be a better name 
    class PortalBundle extends Bundle
    {
        public function getContainerExtension()
        {
            return new AppContextExtension();
        }
    }
    

    分机

    namespace Portal\Common\Infrastructure\Symfony\DependencyInjection;
    
    use Symfony\Component\DependencyInjection\ContainerBuilder;
    use Symfony\Component\DependencyInjection\Extension\Extension;
    
    class AppContextExtension extends Extension
    {
        public function load(array $configs, ContainerBuilder $container)
        {
            dump('it work');die;
        }
    }
    

    config/bundles.php配置

    Portal\Common\Infrastructure\Symfony\PortalBundle::class => ['all' => true],
    

    作曲家.json

    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "Portal\\Common\\Infrastructure\\Symfony\\": "portal/src/Symfony/"
        }
    },
    

    这一切如期而至,但你对autowire的评论让我怀疑你是在试图完全做别的事情。autowire通常用于应用程序定义的服务。您不会自动连接捆绑包。

    享受

        2
  •  0
  •   famas23    8 年前

    实际上,解决方案是将扩展类注入appkernel中,因为可以使用 Kernel::build() .

    //AppKernel.php
    
    class AppKernel extends Kernel
    {
        //
    
        protected function build(ContainerBuilder $container)
        {
            $container->registerExtension(new \Portal\Common\Infrastructure\Symfony\DependencyInjection\AppExtension());
        }
    

    谢谢@cerad帮我找到了路。