如何从侦听器访问存储库

时间:2014-11-19 19:49:16

标签: php symfony doctrine repository

我想向订阅者提出数据库请求

从存储库:我很容易使用以下内容(对于我想要检索id = 1的用户的例子实体用户。

 $repository = $this->getDoctrine()->getManager->getRepository('NameBundle:User');
 $user = $repository->find(1);

但我怎样才能从嫌疑人那里做到这一点。

这里我尝试了...(没有成功,因为我从Symfony2获得以下内容:" FatalErrorException:错误:调用未定义的方法Sdz \ BlogBu​​ndle \ Form \ EventListener \ Subscriber :: getEntityManager()&#34 ;

namespace Sdz\BlogBundle\Form\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Doctrine\ORM\EntityRepository;

class TraductionSubscriber implements EventSubscriberInterface
{
  public static function getSubscribedEvents()
  {
    return array(FormEvents::PRE_SET_DATA => 'preSetData');
  }


  public function preSetData(FormEvent $event)
  {
    $form = $event->getForm();      
    $datas = $event->getData(); 

    $userexist == 'no'

    foreach ($datas as $data){
        if ($data->getUser()->getId() == 1)     { $userexist = 'yes'; $user= $data->getUser();  }
    } 

    if ($userexist == 'no') {
        $repository = $this->getEntityManager()->getRepository('SdzBlogBundle:User');
        $user = $repository->find(1);
    }   

    $form
    ->add('notes', 'collection', array(
                    'type' => new NoteType,
                    'label' => $user->getName(),
                    'required' => false,
                    ));
  }
}

2 个答案:

答案 0 :(得分:0)

将它传递给构造函数(如果它不是服务):

class TraductionSubscriber implements EventSubscriberInterface
{
  private $em;

  public function __construct(EntityManagerInterface $em)
  {
      $this->em = $em;
  }

  ...

并使用:

new TraductionSubscriber($em);

答案 1 :(得分:-1)

您可以通过容器获取 Doctrine 对象。

use Symfony\Component\DependencyInjection\ContainerInterface;

[...]

$this->container->get('doctrine')->getManager();