如何在控制器外的类中使用Doctrine?
$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:
services:
eventService:
class: Atotrukis\MainBundle\Service\EventService
来自EventController的部分:
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;
}
}
答案 0 :(得分:2)
您可以在服务声明中将其作为参数传递:
services:
eventService:
class: Atotrukis\MainBundle\Service\EventService
arguments: ["@doctrine.orm.entity_manager"]
然后只需在你的类中添加一个构造函数:
protected $em;
public function __construct($em)
{
$this->em = $em
}