根据第三方包中的配置使用服务进入服务

using service into service depending on configuration in thrid-party bundle

我正忙于将我的第三方包从 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 移动到第三方捆绑包之外的主要 service.yaml 部分,则它不会。这意味着任何使用我的第三方包的人仍然不能使用另一个 userChecker。我试过类似的东西:

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

但它给出了一个字符串作为结果而不是一个实例。 有人给我线索吗?

您必须在扩展中配置您的服务 class

<?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"]));
    }
}