根据第三方捆绑中的配置将服务用于服务

时间:2019-02-02 10:09:18

标签: symfony symfony4

我正忙于将第三方捆绑软件从symfony 3移植到symfony 4。 我在此捆绑包中拥有自己的服务。我们称之为MyService:

use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;

class MyService
{
    private $params;
    private $userChecker;

    function __construct( ParameterBagInterface $params,
                          UserCheckerInterface  $userChecker )
    {
        $this->params = $params;
        $this->userChecker = $userChecker;
    }

    // ...
}

我在第二次注入“ UserCheckerInterface”时遇到问题,该问题必须注入另一个容器服务,具体取决于我的捆绑软件配置。

MyBundle / DependencyInjection / Configuration.php:

class Configuration implements ConfigurationInterface
{
    /**
     * {@inheritdoc}
     */
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('fbeen_user');

        $rootNode
            ->children()
                ->scalarNode('user_checker')->defaultValue('@security.user_checker.main')->end()
            ->end()
        ;

        return $treeBuilder;
    }

}

最后在我的捆绑包中的services.yaml:

services:
    _defaults:
        bind:
            $userChecker: '@security.user_checker.main'

    my_bundle.my_service:
        class: MyCompany\MyBundle\Service\MyService
        arguments: ['@parameter_bag'] 
        public: true

这可行,但是如果我将_defaults:绑定部分从捆绑包的service.yaml移至第三方捆绑包之外的main service.yaml,则不能。这意味着使用我的第三方捆绑软件的任何人仍然不能使用另一个userChecker。我尝试过类似的事情:

services:
    _defaults:
        bind:
            $userChecker: '@%mycompany_mybundle.user_checker%'

,但它给出结果字符串而不是实例。 有人对我有帮助吗?

1 个答案:

答案 0 :(得分:1)

您必须在扩展类中配置服务

<?php

namespace MyBundle\DependencyInjection;

use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\DependencyInjection\Loader;
use Symfony\Component\DependencyInjection\Reference;

class MyBundleExtension extends Extension 
{
    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');

        $definition = $container->getDefinition('my_bundle.my_service');
        $definition->replaceArgument(1, new Reference($config["user_checker"]));
    }
}