Reputation: 37
When I inject a service into another via constructor injection, the constructor of the injected class is not being called. Has anyone an explanation for this. What am I overlooking?
I created this little sample for demonstration purposes:
services.yml
services:
foo.A:
class: Acme\FooBundle\A
foo.B:
class: Acme\FooBundle\B
arguments:
a: "@foo.A"
Class A:
<?php
namespace Acme\FooBundle;
class A
{
public function __construct()
{
echo "constructing A\n";
}
}
Class B:
<?php
namespace Acme\FooBundle;
class B
{
public function __construct($a)
{
echo "constructing B\n";
}
}
Testcode:
echo "\nTest A ----------------------\n";
$this->getContainer()->get('foo.A');
echo "\nTest B ----------------------\n";
$this->getContainer()->get('foo.B');
Output:
Test A ---------------------- constructing A
Test B ---------------------- constructing B
When retrieving 'foo.B' I'd expect that also A's constructor would be called.
Upvotes: 0
Views: 1066
Reputation: 7428
As you've called $this->getContainer()->get('foo.A');
before $this->getContainer()->get('foo.B');
there is already instance of class A
so it's not created again.
Try to call only $this->getContainer()->get('foo.B');
and you'll get output of both constructors
Upvotes: 1