编程语言
首页 > 编程语言> > php – Symfony – 使用另一个捆绑服务

php – Symfony – 使用另一个捆绑服务

作者:互联网

我正在尝试使用另一个捆绑包中的服务,而不会在捆绑包之间创建任何依赖关系.我正在尝试使用CompilerPass,但这可能不是最好的方法.

我在BarBundle中创建了一个ParamConverter,FooBundle应该为它的控制器使用它.

但是我收到错误:没有找到名为foo_bundle.converter_service的转换器来转换参数fooObject

到目前为止我所拥有的:

应用程序/配置/ config.yml

foo_bundle:
    converter_service: bar_bundle.converter.object

SRC / BarBundle /配置/ service.yml

services:
    bar_bundle.converter.object:
        class: BarBundle\ParamConverter\ObjectParamConverter
        tags:
            - { name: request.param_converter, priority: 0, converter: bar_bundle.converter.object }

SRC / FooBundle / DependencyInjection / FooBundleExtension.php

public function load(array $configs, ContainerBuilder $container)
{
    $configuration = new Configuration();
    $config = $this->processConfiguration($configuration, $configs);

    $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
    $loader->load('services.yml');

    $container->setParameter('foo_bundle.converter_service.id', $config['converter_service']);
}

SRC / FooBundle / FooBundle.php

public function build(ContainerBuilder $container)
{
    parent::build($container);

    $container->addCompilerPass(new CompilerPass());
}

SRC / FooBundle / DependencyInjection / CompilerPass.php

public function process(ContainerBuilder $container)
{
    $convertserService = $container->getDefinition($container->getParameter('foo_bundle.converter_service.id'));
    $container->setDefinition('foo_bundle.converter_service', $convertserService);
}

控制器注释:

/**
 * Show Feed document.
 *
 * @Route("/{id}/add", name="object_add")
 * @ParamConverter("fooObject", converter="foo_bundle.converter_service")
 */
public function addAction(ObjectInterface $fooObject)

如果我在CompilerPass中调用$container-> get(‘foo_bundle.converter_service’),我可以看到对象正确设置.

这是一个优先问题吗?即是解析注释后运行的CompilerPass.或者这只是错误的做法?

解决方法:

由于@ParamConverter也加载了CompilerPass,您可能必须先强制​​执行.

请注意,默认编译器传递优先级为0且优先级越高,执行越早.

试试这个 :

public function build(ContainerBuilder $container)
{
    parent::build($container);
    $container->addCompilerPass(new CompilerPass(), PassConfig::TYPE_BEFORE_OPTIMIZATION, 30);
}

标签:php,symfony,symfony3-4
来源: https://codeday.me/bug/20190710/1425862.html