Symfony中的依赖注入

时间:2017-06-24 15:19:48

标签: php symfony dependency-injection

我正在构建Symfony 3.3应用程序。我在Console文件夹中有一个帮助器:

abstract class AbstractHelper implements HelperInterface
{
    protected $httpClient;

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

我在服务文件夹中实现了名为 HttpGuzzle HttpInterface 。我怎么能帮助Symfony弄清楚我想将 HttpGuzzle 注入 AbstractHelper 构造函数?我试图将这些行添加到services.yml但它不起作用:

AppBundle\Command\AbstractHelper:
    arguments:
        $httpClient: AppBundle\Service\HttpGuzzle

如果我运行测试,则会抛出错误:

ArgumentCountError: Too few arguments to function AppBundle\Command\AbstractHelper::__construct(), 
0 passed in ~/Projects/app/tests/AppBundle/Console/HelperTest.php 
on line 17 and exactly 1 expected

有了这个:

helper:
    class: AppBundle\Command\AbstractHelper:
    arguments: [AppBundle\Service\HttpGuzzle]

我收到错误:

You have requested a non-existent service "helper".

1 个答案:

答案 0 :(得分:1)

services.yml您必须定义 HttpGuzzle 服务本身,如下所示:

httpguzzle:
    class: AppBundle\Service\HttpGuzzle

然后你可以像这样使用传递给助手:

helper:
    class: AppBundle\Command\AbstractHelper
    arguments: ["@httpguzzle"]