Get Doctrine or pass in service without using __construct - Symfony2

痞子三分冷 提交于 2020-01-03 04:52:22

问题


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));


来源:https://stackoverflow.com/questions/17998461/get-doctrine-or-pass-in-service-without-using-construct-symfony2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!