Php Symfony中的依赖注入
我正在构建Symfony 3.3应用程序。我在控制台文件夹中有一个助手:Php Symfony中的依赖注入,php,symfony,dependency-injection,Php,Symfony,Dependency Injection,我正在构建Symfony 3.3应用程序。我在控制台文件夹中有一个助手: abstract class AbstractHelper implements HelperInterface { protected $httpClient; public function __construct(HttpInterface $httpClient) { $this->httpClient = $httpClient; } } 我将名为Http
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
You have requested a non-existent service "helper".
为此:
helper:
class: AppBundle\Command\AbstractHelper:
arguments: [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
You have requested a non-existent service "helper".
在
services.yml
中,您必须定义HttpGuzzle服务本身,如下所示:
httpguzzle:
class: AppBundle\Service\HttpGuzzle
helper:
class: AppBundle\Command\AbstractHelper
arguments: ["@httpguzzle"]
然后,您可以使用如下方式将其传递给帮助器:
httpguzzle:
class: AppBundle\Service\HttpGuzzle
helper:
class: AppBundle\Command\AbstractHelper
arguments: ["@httpguzzle"]
谢谢我刚刚处理了这个问题。但当我试图从测试中获得服务时,它似乎不起作用<代码>静态::createClient()->getContainer()->get('helper')代码>我收到关于不存在服务的相同错误。您确定是相同的错误吗?你能把它寄出去吗?您试图实例化一个抽象类的事实可能与此有关。