I would like to use EntityManager in self-made Service
in my config.yml
services:
myfunc:
class: Acme\TopBundle\MyServices\MyFunc
arguments: []
in Acme\TopBundle\MyServices\MyFunc.php
namespace Acme\TopBundle\MyServices;
use Doctrine\ORM\EntityManager;
class MyFunc
{
public $em;
public function check(){
$this->em = $this->getContainer()->get('doctrine')->getEntityManager(); // not work.
.
.
it shows error when I call method check().
Call to undefined method Acme\TopBundle\MyServices\MyFunc::getContainer()
How can I use getContainer() in myFunc class??
You need to make MyFunc "container aware":
Your service:
I should point out that injecting a container is usually not required and is frowned upon. You could inject the entity manager directly into MyFunc. Even better would be to inject whatever entity repositories you need.
As you (fortunately) didn't inject the container in your
myfunct
service, there's no available reference to the container within your service.You may not neeed to get the entity manager via the service container! Keep in mind that the DIC allows you to customise your services by injecting only the relevant services they need (the entity manager in your case)
Your service definition,
Also,