gpt4 book ai didi

php - symfony v3.4 无法猜测 Autowiring

转载 作者:搜寻专家 更新时间:2023-10-31 20:58:24 25 4
gpt4 key购买 nike

Symfony v3.4 在使用 Autowiring 功能时无法猜测参数。

Cannot autowire service "AppBundle\Service\MyServiceConfig": argument "$key" of method "__construct()" has no type-hint, you should configure its value explicitly.

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

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

最佳答案

所以我很无聊。将您的 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。因此, Autowiring 在容器中查找 ID 为 MyAppServiceInterface 的服务。它根本不查看类参数。现在,在您的情况下,您有 MyAppService 实现您的接口(interface), Autowiring 足够智能,可以识别您的接口(interface)只有一个实现。

如果您决定添加另一个实现,请更稳健一点,将您的实现显式别名到接口(interface),以防止出现问题。在这种情况下并非绝对必要。

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

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

还有一件不相关的事情:不要调用你的 twig 扩展类 AppBundleExtension。似乎您将 Twig 扩展与捆绑扩展混为一谈。两个不同的概念。并不重要,但它可能会让人感到困惑。

关于php - symfony v3.4 无法猜测 Autowiring ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50154741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com