2014-10-31 2 views
0

Doctrine을 컨트롤러 외부의 클래스에서 어떻게 사용합니까?서비스에서 Doctrine 사용하기 Symfony2

$event = $this->getDoctrine() 
    ->getRepository('AtotrukisMainBundle:Event') 
    ->findByCreatedBy($userId); 
if (!$event) { 
    throw $this->createNotFoundException(
     'You have no events' 
    ); 
} 

위의 코드는 컨트롤러에서 완벽하게 작동하지만, 서비스에서 나는 오류 얻을 : 나는 그것을 작동하게하려면 어떻게 Attempted to call method "getDoctrine" on class "Atotrukis\MainBundle\Service\EventService" in /var/www/src/Atotrukis/MainBundle/Service/EventService.php line 15.

를?

services.yml :

public function readMyEventsAction() 
{ 
    $user = $this->getDoctrine()->getRepository('AtotrukisMainBundle:User') 
     ->findOneById($this->get('security.context')->getToken()->getUser()->getId()); 

    $userEvents = $this->get('eventService')->readUserEvents($user); 

    return $this->render('AtotrukisMainBundle:Event:myEvents.html.twig', array('events' => $userEvents)); 
} 

EventService.php :

<?php 
namespace Atotrukis\MainBundle\Service; 

class EventService{ 

    public function create(){ 


    } 
    public function readUserEvents($userId){ 

     $event = $this->getDoctrine() 
      ->getRepository('AtotrukisMainBundle:Event') 
      ->findByCreatedBy($userId); 
     if (!$event) { 
      throw $this->createNotFoundException(
       'You have no events' 
      ); 
     } 
     return $userId; 
    } 

} 

답변

2

당신은 당신의 서비스 선언에 인수로 전달할 수 EventController에서

services: 
    eventService: 
     class: Atotrukis\MainBundle\Service\EventService 

부 :

services: 
    eventService: 
     class: Atotrukis\MainBundle\Service\EventService 
     arguments: ["@doctrine.orm.entity_manager"] 

그럼 그냥 클래스에 생성자를 추가

protected $em; 

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