Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add the Entity Manager to a custom class or service?

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.

like image 484
Nick Avatar asked Nov 05 '11 17:11

Nick


People also ask

Is it possible to create another class in entity manager?

} And if you still need to use the Entity Manager you can create another class. This should be in your pom.xml

How to create a custom entity in unmanaged solution?

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.

Can I use an existing entity for a custom 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.

How to create custom entity in Salesforce?

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.


Video Answer


2 Answers

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.

like image 180
dylan oliver Avatar answered Oct 17 '22 12:10

dylan oliver


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

like image 28
Steven Mercatante Avatar answered Oct 17 '22 14:10

Steven Mercatante