I've created my own service and I need to inject doctrine EntityManager, but I don't see that __construct()
is called on my service, and injection doesn't work.
Here is the code and configs:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManager;
class UserService {
/**
*
* @var EntityManager
*/
protected $em;
public function __constructor(EntityManager $entityManager)
{
var_dump($entityManager);
exit(); // I've never saw it happen, looks like constructor never called
$this->em = $entityManager;
}
public function getUser($userId){
var_dump($this->em ); // outputs null
}
}
Here is services.yml
in my bundle
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments:
entityManager: "@doctrine.orm.entity_manager"
I've imported that .yml in config.yml
in my app like that
imports:
# a few lines skipped, not relevant here, i think
- { resource: "@TestCommonBundle/Resources/config/services.yml" }
And when I call service in controller
$userservice = $this->get('test.common.userservice');
$userservice->getUser(123);
I get an object (not null), but $this->em
in UserService is null, and as I already mentioned, constructor on UserService has never been called
One more thing, Controller and UserService are in different bundles (I really need that to keep project organized), but still: everyting else works fine, I can even call
$this->get('doctrine.orm.entity_manager')
in same controller that I use to get UserService and get valid (not null) EntityManager object.
Look like that I'm missing piece of configuration or some link between UserService and Doctrine config.
Your class's constructor method should be called __construct()
, not __constructor()
:
public function __construct(EntityManager $entityManager)
{
$this->em = $entityManager;
}
For modern reference, in Symfony 2.4+, you cannot name the arguments for the Constructor Injection method anymore. According to the documentation You would pass in:
services:
test.common.userservice:
class: Test\CommonBundle\Services\UserService
arguments: [ "@doctrine.orm.entity_manager" ]
And then they would be available in the order they were listed via the arguments (if there are more than 1).
public function __construct(EntityManager $entityManager) {
$this->em = $entityManager;
}
Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.
namespace AppBundle\Service;
use Doctrine\ORM\EntityManagerInterface;
class Someclass {
protected $em;
public function __construct(EntityManagerInterface $entityManager)
{
$this->em = $entityManager;
}
public function somefunction() {
$em = $this->em;
...
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With