James May
James May

Reputation: 1537

Dependency Injection in Symfony

I'm building Symfony 3.3 application. I have a helper in a Console folder:

abstract class AbstractHelper implements HelperInterface
{
    protected $httpClient;

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

And I have implementation of HttpInterface named HttpGuzzle into Service folder. How could I help Symfony to figure out I want to inject HttpGuzzle into AbstractHelper constructor? I tried to add these line to services.yml but it doesn't work:

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

If i run the tests it throws an error:

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

With this:

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

I get an error:

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

Upvotes: 0

Views: 291

Answers (1)

Francesco Abeni
Francesco Abeni

Reputation: 4265

In services.yml You have to define the HttpGuzzle service itself, like this:

httpguzzle:
    class: AppBundle\Service\HttpGuzzle

Then you can use pass it to the helper like this:

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

Upvotes: 1

Related Questions