Symfony 3.3服务自动配置

6

我想迁移到Symfony 3.3并使用新功能autowire/autoconfigure服务:

因此,在services.yml中,我有:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false

    # makes classes in src/AppBundle available to be used as services
    AppBundle\:
        resource: '../../src/AppBundle/*'
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Controller,DQL,Form/DataTransformer,Repository}'

我声明我的Twig扩展如下:

AppBundle\Twig\ImageExtension:
      arguments:
          $env: "%kernel.environment%"

这项服务的构造函数:

public function __construct(TokenStorage $token, UserRepository $userRepository, RedisCacheService $cache, string $env)
{
    $this->env = $env;
    $this->user = $token->getToken() ? $token->getToken()->getUser() : false;
    $this->userRepository = $userRepository;
    $this->cache = $cache;
}

看起来一切都没问题,但我仍然收到这个错误:

(1/1) AutowiringFailedException
Cannot autowire service "AppBundle\Twig\ImageExtension": argument "$env" of method "__construct()" must have a type-hint or be given a value explicitly.

我不知道如何解决这个问题。


1
唉,自动装配只适用于类。不能使用字符串或整数。你可以创建一个包装$env的类,但是这种自动装配风潮不会持续太久。https://dev59.com/kqLia4cB1Zd3GeqPh1kD - Cerad
1
@kRicha并没有谈论自动装配env参数,他谈论的是他的配置无法工作。根据手动绑定的官方文档,他的配置看起来是正确的。 @kRicha:你确定你将Symfony依赖项更新到3.3+吗? - Noémi Salaün
@NoémiSalaün 没错 - kRicha
也许你应该尝试完全配置参数,并查看是否可以找到为什么它不起作用的解释。您还可以尝试通过索引进行配置,使用3而不是$env。或者对其他三个服务使用空引号。argument: ['', '', '', '%kernel.environment%] - Noémi Salaün
你有没有找到一种使用自动装配传递参数的方法?只是好奇。 - Cerad
@Cerad,请检查我的答案。 - kRicha
2个回答

4

我也遇到了同样的错误信息,但是原因不同。或许有人会发现这个信息有用。

我的service.yml文件中最初的配置如下:

app.my_service:
    class: 'AppBundle\Service\MyService'
    arguments:
        $foobar: 'some value for foobar'
    public: true

我遇到了以下错误:

无法自动装配服务“AppBundle\Service\MyService”:方法“__construct()”的参数“$ foobar”必须具有类型提示或显式地给出一个值。

几个小时后,我找到了解决办法:

AppBundle\Service\MyService:
    arguments:
        $foobar: 'some value for foobar'

app.my_service:
    alias: AppBundle\Service\MyService
    public: true

2

问题出在我试图使用AppBundle中的services.yml文件上,如果我理解正确的话,旧的从bundles导入服务的方式无法与自动装配/自动配置一起使用,因为我们需要重写load()方法并使用类型提示。所以我把所有的服务替换成了app/config/services.yml,这帮助了我。


我有非常类似的问题,但我不明白你具体做了什么。你能否请再详细解释一下答案?谢谢。 - DamirR
@DamirR 嘿,试着将配置从service.yml(例如AppBundle)移动到app/config中的service.yml。 - kRicha
感谢您的快速回复。我的service.yml一直在app/config/中,但仍然无法正常工作。与此同时,我已经找到了解决问题的方法。 我无法在评论中格式化多行代码块,所以我会将其添加为答案。希望您不介意。 - DamirR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接