【问题标题】:symfony v3.4 unable to guess autowiringsymfony v3.4 无法猜测自动装配
【发布时间】:2018-10-13 17:59:47
【问题描述】:

Symfony v3.4 在使用自动连线功能时无法猜测参数。

无法自动装配服务“AppBundle\Service\MyServiceConfig”:方法“__construct()”的参数“$key”没有类型提示,您应该明确配置其值。

我也明确定义了参数,但它仍然不起作用,参数类型为string,长度为 136 个字符。

services:
     app.myservice.config:
         class: AppBundle\Service\MyServiceConfig
         public: true
         arguments: ["%app_key%"] #defined in parameter.yml

    app.myservice
         class: AppBundle\Service\MyService
         public: true
         arguments: ["@app.myservice.config"]

效果非常好,当我调用服务时,我可以看到预期的结果。

但是,当我编写 AppExtension 时,出现上述错误:

app.twig.my_app_extension:
    class: AppBundle\Twig\MyAppExtension
    arguments: [ "@app.myservice" ]
    tags:
       - { name: twig.extension }

所以我明确定义了参数

app.myservice.config:
     class: AppBundle\Service\MyServiceConfig
     public: true
     arguments: 
         $key:  "%app_key%" #defined in parameter.yml

还是不行

这是 MyServiceConfig 类的样子:

 class MyServiceConfig implements MyServiceConfigInterface {

    /**
     * @var string
     */
    private $key;

   public function __construct($key){
    $this->key= $key;
 }
}

MyAppExtension 类:

/**
 * The MyAppExtension class
 */
 class MyAppExtension extends \Twig_Extension
  {
  /**
   * @var MyServiceConfigInterface $key
   */
  private $key;

  public function __construct(MyServiceConfigInterface $key){
    $this->key= $key;
  }
}

here 提供的解决方案也没有帮助,因为我在app/config/services.yml 中有我的 service.yml

【问题讨论】:

  • 使用 AppBundle\Twig\MyAppExtension 代替 app.twig.my_app_extension 作为服务 ID。我认为正在发生的事情是 autowire 的自动服务检测正在拿起你的课程并尝试自动装配它。
  • 如果你尝试怎么办:public function __construct(string $key)
  • @Cerad 和 Sylvain Attoumani 我尝试了这两个建议,但它不起作用。但是我创建了一个简单的应用程序来复制错误。 link to the project
  • 想想吧。 Autowire 是关于类和类名的。它不知道如何处理 app.myservice.config 和 app.myservice 很好地将您的问题减少到单个 repo。现在创建另一个新项目并按照文档中的示例进行操作。

标签: php symfony


【解决方案1】:

所以我很无聊。将您的 app/config/services.yml 文件更新为:

#app.myservice.config:
AppBundle\Service\MyServiceConfig:
#    public: true
    arguments:
        $key: "%key%"

#app.myservice:
#    class: AppBundle\Service\MyAppService
#    arguments: ["@app.myservice.config"]
#    public: true

您的 TwigExtension 类型提示针对 MyAppServiceInterface。因此,autowire 在容器中查找 ID 为 MyAppServiceInterface 的服务。它根本不看类参数。现在,在您的情况下,您的 MyAppService 实现了您的接口,并且 autowire 足够聪明,可以识别出您的接口只有一个实现。

如果您决定添加另一个实现,请将您的实现显式别名为接口以防止出现问题。在这种情况下不是绝对必要的。

AppBundle\Service\MyServiceConfig:
    { $key: "%key%" } # Just showing off here

AppBundle\Service\MyServiceConfigInterface: '@AppBundle\Service\MyServiceConfig'

还有一件不相关的事情:不要调用你的树枝扩展类 AppBundleExtension。似乎您将树枝扩展与捆绑扩展混合在一起。两个不同的概念。没关系,但可能会让人感到困惑。

【讨论】:

    猜你喜欢
    • 2018-11-02
    • 1970-01-01
    • 2018-06-06
    • 1970-01-01
    • 2023-03-16
    • 2020-02-09
    • 2018-09-17
    • 1970-01-01
    • 2018-08-05
    相关资源
    最近更新 更多