4

In a Symfony2 project, when you use a Controller, you can access Doctrine by calling getDoctrine() on this, i.e.:

$this->getDoctrine();

In this way, I can access the repository of such a Doctrine Entity.

Suppose to have a generic PHP class in a Symfony2 project. How can I retrieve Doctrine ? I suppose that there is such a service to get it, but I don't know which one.

Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
JeanValjean
  • 17,172
  • 23
  • 113
  • 157

2 Answers2

11

You can register this class as a service and inject whatever other services into it. Suppose you have GenericClass.php as follows:

class GenericClass
{
    public function __construct()
    {
        // some cool stuff
    }
}

You can register it as service (in your bundle's Resources/config/service.yml|xml usually) and inject Doctrine's entity manager into it:

services:
    my_mailer:
        class: Path/To/GenericClass
        arguments: [doctrine.orm.entity_manager]

And it'll try to inject entity manager to (by default) constructor of GenericClass. So you just have to add argument for it:

public function __construct($entityManager)
{
     // do something awesome with entity manager
}

If you are not sure what services are available in your application's DI container, you can find out by using command line tool: php app/console container:debug and it'll list all available services along with their aliases and classes.

Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
  • This will inject the EntityManager. How can I get a repository through it? In a controller I can get the repository as follows: `$this->getDoctrine() ->getRepository('AcmeUserBundle:Address');`, and I can also get the EntityManager as follows: `$this->getDoctrine()->getEntityManager()`. However, known the EntityManager, how can I get the repository? If I can, then the answer is your! – JeanValjean Aug 10 '12 at 17:34
  • 1
    If you look at `getDoctrine` in base `Controller` class it just calls `$this->container->get('doctrine')`. So you can do the same with your service (inject `doctrine` into it). But you can achieve the same by calling `$entityManager->getRepository('...')`. – Ondrej Slinták Aug 10 '12 at 17:42
  • Doesn't work for me, I get a "Missing argument"-warning although the service is registered correctly (I can see it using "console container:debug"). – Select0r Sep 29 '16 at 14:47
1

After checking the symfony2 docs i figured out how to pass your service in a custom method to break the default behavior.

Rewrite your configs like this:

services:
my_mailer:
    class: Path/To/GenericClass
    calls:
         - [anotherMethodName, [doctrine.orm.entity_manager]]

So, the Service is now available in your other method.

public function anotherMethodName($entityManager)
{
    // your magic
}

The Answer from Ondrej is absolutely correct, I just wanted to add this piece of the puzzle to this thread.

Boris Kotov
  • 1,782
  • 2
  • 13
  • 14