2017-06-24 112 views
0

我正在構建Symfony 3.3應用程序。我有一個控制檯文件夾中的幫手:Symfony中的依賴注入

abstract class AbstractHelper implements HelperInterface 
{ 
    protected $httpClient; 

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

我有實現的HttpInterface命名HttpGuzzle到服務的文件夾。我怎麼能幫助Symfony找出我想注入HttpGuzzle摘要幫助構造函數?我嘗試添加這些行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

services.yml你必須定義HttpGuzzle服務本身,就像這樣:

httpguzzle: 
    class: AppBundle\Service\HttpGuzzle 

這時你可以用它傳遞給這樣的幫手:

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

感謝。我剛剛處理了這個問題。但是當我試圖從測試中獲得服務時似乎不起作用。 'static :: createClient() - > getContainer() - > get('helper');'我得到了關於不存在的服務的相同錯誤。 –

+0

你確定它是一樣的錯誤嗎?你可以發佈嗎?你試圖抽象類的實例可能與它有關。 –