In Symfony2, how can I go about adding Doctrine's entity manager to a custom class or service?
I have tried $em = $this->get("doctrine.orm.entity_manager");
and $em = $this->getDoctrine()->getEntityManager();
Both failed, which led me to try and extend the Controller class with my custom class/service, and that died in a giant ball of fire.
} And if you still need to use the Entity Manager you can create another class. This should be in your pom.xml
You need to open setting, solution, select your unmanaged solution and under Entitys you can create your custom entitiy. Inside the case after you need to create the right relation 1:N with the new entity.
Before you create a custom entity, evaluate whether using an existing entity will meet your requirements. More information: Create new metadata or use existing metadata Part of the name of any custom entity you create is the customization prefix. This is set based on the solution publisher for the solution you’re working in.
You need first of all create your custom entity and create a relation between case and your custom entity after you can manage it. You need to open setting, solution, select your unmanaged solution and under Entitys you can create your custom entitiy.
You do not have to define your controller as a service in order to access the EntityManager. The Controller::getDoctrine()
method mentioned above simply returns the Doctrine Registry by calling $this->container->get('doctrine')
after checking that the doctrine service is actually available.
Simply make your custom class/controller extend ContainerAware
and define a shortcut method like:
public function getEntityManager() {
return $this->container->get('doctrine')->getEntityManager();
}
Note that it's $this->container->get(..)
and not $this->get(..)
in a class extending/implementing ContainerAware
.
You need to inject the entity manager service into your custom service. Your service definition should look like this:
my.service.name:
class: my\class
arguments: [ @doctrine.orm.default_entity_manager ]
Make sure that your service's __construct
method takes the entity manager as an argument.
See the Service Container chapter for more info.
BTW, $this->getDoctrine()
is a shortcut method that will only work in a class that extends Symfony\Bundle\FrameworkBundle\Controller\Controller
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