在服务中使用条令Symfony2
如何在控制器之外的类中使用条令在服务中使用条令Symfony2,symfony,doctrine-orm,Symfony,Doctrine Orm,如何在控制器之外的类中使用条令 $event = $this->getDoctrine() ->getRepository('AtotrukisMainBundle:Event') ->findByCreatedBy($userId); if (!$event) { throw $this->createNotFoundException( 'You have no events' ); } 上面的代码在控制器中工作得很好
$event = $this->getDoctrine()
->getRepository('AtotrukisMainBundle:Event')
->findByCreatedBy($userId);
if (!$event) {
throw $this->createNotFoundException(
'You have no events'
);
}
上面的代码在控制器中工作得很好,但在服务中我得到了一个错误:试图在/var/www/src/Atotrukis/MainBundle/service/EventService.php第15行中的类“Atotrukis\MainBundle\service\EventService”上调用方法“getdoctor”。
我如何让它工作
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;
}
}
您可以在服务声明中将其作为参数传递:
services:
eventService:
class: Atotrukis\MainBundle\Service\EventService
arguments: ["@doctrine.orm.entity_manager"]
然后只需向类中添加构造函数:
protected $em;
public function __construct($em)
{
$this->em = $em
}