首页 > 解决方案 > Symfony 注入一个字符串而不是服务

问题描述

我有这个 Symfony 5.1 应用程序,我试图在其中注入自定义缓存适配器实现,但它注入了一个字符串t72YSNXSq7

这是我的配置:

缓存.yaml

framework:
    cache:
        pools:
            stories:
                name: cache.stories
                adapter: Rikudou\DynamoDbCacheBundle\Cache\DynamoDbCacheAdapter

捆绑包配置(两个文件)如下(它适用于其他 Symfony 应用程序):

services:
  rikudou.dynamo_cache.cache: # arguments defined in extension
    class: Rikudou\DynamoDbCache\DynamoDbCache
    arguments:
      $clock: ~
      $converter: '@rikudou.dynamo_cache.converter_registry'

  rikudou.dynamo_cache.adapter:
    class: Rikudou\DynamoDbCacheBundle\Cache\DynamoDbCacheAdapter
    arguments:
      - '@rikudou.dynamo_cache.cache'
services:
  Rikudou\DynamoDbCacheBundle\Cache\DynamoDbCacheAdapter: '@rikudou.dynamo_cache.adapter'
  Rikudou\DynamoDbCache\DynamoDbCache: '@rikudou.dynamo_cache.cache'

我的应用services.yaml(相关部分):

services:
    _instanceof:
        App\DependencyInjection\StoriesCacheInterface:
            tags:
                - app.stories_cache

然后我有这个编译器通过,它将cache.stories服务用于标记为的服务app.stories_cache,例如那些实现App\DependencyInjection\StoriesCacheInterface

    public function process(ContainerBuilder $container): void
    {
        $services = array_keys($container->findTaggedServiceIds('app.stories_cache'));
        foreach ($services as $service) {
            $service = $container->getDefinition($service);
            $reflection = new ReflectionClass($service->getClass());
            $constructor = $reflection->getConstructor();
            if ($constructor === null) {
                continue;
            }
            $arguments = $constructor->getParameters();
            foreach ($arguments as $argument) {
                if (!($type = $argument->getType())) {
                    continue;
                }
                if ((string) $type !== AdapterInterface::class) {
                    continue;
                }
                $service->setArgument('$' . $argument->getName(), new Reference('cache.stories'));
            }
        }
    }

最后,这是生成的容器文件,它注入t72YSNXSq7而不是(为了更好的可读性而缩进)的实例Rikudou\DynamoDbCache\DynamoDbCache

        return $container->services['App\\Controller\\AuthorController'] = new \App\Controller\AuthorController(
            new \App\Service\AuthorReader(
                (
                    $container->privates['cache.stories'] ?? (
                        $container->privates['cache.stories'] = new \Rikudou\DynamoDbCacheBundle\Cache\DynamoDbCacheAdapter('t72YSNXSq7') // the wrong line
                    )
                ),
                ($container->privates['App\\Service\\StorySearcher'] ?? $container->load('getStorySearcherService')), 
                ($container->privates['App\\Service\\Downloader'] ?? ($container->privates['App\\Service\\Downloader'] = new \App\Service\Downloader()))),
            $a
        );

标签: phpsymfonysymfony5

解决方案


推荐阅读