Get Doctrine or pass in service without using __co

2019-06-13 08:46发布

问题:

I'm trying to extend a class, but I have this problem:

(1) I need to conduct a simple database query, but if I pass in @doctrine.orm.entity_manager in services.yml I then need to pass a load of other values in and call parent::__construct (for the parent class) and I just can't get it working (another question exists for that but no luck).

(2) If I don't create a __construct in my new extended class then it works but I can't get access to conduct the DB query.

Is there a way of getting access to Doctrine, conducting a query, passing in @doctrine.orm.entity_manager or anything so I can conduct this query without having to call a _construct on my new, extended class (and avoid having to pass in all those variables to then call the parent::_construct which is causing such a problem).

As I have been trying to do this for 2 days then I will take any hack if I have to (preferably not too much of a hack, but I may need to if I can't do this soon). To date I have never resorted to a hack with Symfony2, so this isn't usual for me. Thanks.

回答1:

You can use setter injection if you don't want to inject the arguments into the constructor.

Service Configuration

 my_service:
     class: YourClass
     calls:
         - [setEntityManager, ["@doctrine.orm.entity_manager"]]

YourClass

use Doctrine\Common\Persistence\ObjectManager;

// ...

protected $em;

public function setEntityManager(ObjectManager $em)
{
   $this->em = $em;
}

public function someOtherFunction()
{
    $this->em->getRepository('...')
}


回答2:

You want a hack? Here you go:

    $kernel = $GLOBALS['kernel'];
    $em = $kernel->getContainer()->get('doctrine.orm.entity_manager');
    die(get_class($em));