2012-01-11 64 views
9

我們需要訪問偵聽器中的數據庫信息。 我們配置監聽器在service.yml 監聽器是這樣的:在Symfony 2的偵聽器中訪問數據庫

namespace company\MyBundle\Listener; 

use Symfony\Component\HttpKernel\Event\GetResponseEvent; 
use Symfony\Component\HttpKernel\HttpKernelInterface; 
use Symfony\Component\DependencyInjection\ContainerInterface; 
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; 
use Symfony\Component\HttpFoundation\RedirectResponse; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class RequestListener 
{ 
    protected $container; 

public function __construct(ContainerInterface $container) 
{ 
    $this->container = $container; 
} 

public function onKernelRequest(GetResponseEvent $event) 
{ 
... 

我們怎樣才能在onKernelRequest功能訪問的學說?

我試圖從控制器延伸,並做到:

 $em = $this->getDoctrine()->getEntityManager(); 

和它的作品,但我認爲這是一個不好的做法。

+0

感謝所有的意見。所有都是很好的選擇。 – Santi 2012-01-13 15:09:57

回答

27

您可以只注入服務容器。首先改變構造函數來得到一個EntityManager:

use Doctrine\ORM\EntityManager; 

class RequestListener { 
    protected $em; 
    function __construct(EntityManager $em) 
    { 
     $this->em = $em; 
    } 
    //... 
} 

而旁邊配置您的服務:

#... 
services: 
    foo.requestlistener: 
     class: %foo.requestlistener.class% 
     arguments: 
      - @doctrine.orm.entity_manager 
+0

謝謝,是不錯的選擇 – Santi 2012-01-13 15:10:46

+3

這是最好的選擇。 – 2013-02-05 17:08:59

+0

謝謝,一旦我添加了「使用Symfony \ Component \ DependencyInjection \ ContainerInterface;」 – someuser 2013-04-13 13:16:53

2

好像你注射服務容器到監聽器,這樣你就可以訪問主義是這樣的:

$doctrine = $this->container->get('doctrine'); 
1

我是那種在Symfony的新手還是的,但你有沒有試過傳遞doctrine服務給您的監聽器而不是服務容器?

或者,您已經通過服務容器,因此它應該像調用
$this->container->get('doctrine')一樣簡單。另外,前段時間我在IRC被告知,通過服務容器通常被認爲是不好的做法。最好傳遞你需要的單個服務。

+0

謝謝,是不錯的選擇 – Santi 2012-01-13 15:10:13

0

我不會把業務邏輯聽衆爲只對監聽事件。你會如何使用原則爲聽衆編寫測試...

我會將學習訪問的東西放到不同的類中,然後在偵聽器中調用它。

2

如果你的使用情況,您可以使用一個學說事件監聽器directely

#services.yml 
qis.listener.contractBundleStatusListener: 
    class: Acme\AppBundle\EventListener\MyListener 
    tags: 
     - { name: doctrine.event_listener, event: postPersist } 

可以從LifecycleEventArgs獲取實體管理器:

<?php 

use Doctrine\ORM\Event\LifecycleEventArgs; 

class MyListener 
{ 
    public function postPersist(LifecycleEventArgs $args) 
    { 
     $entity = $args->getEntity(); 

     if ($entity instanceof Foo) { 
      $entityManager = $args->getEntityManager(); 

      $entityManager->persist($entity); 
      $entityManager->flush(); 
     } 
    } 
} 
相關問題