Reputation: 1382
How do I use Doctrine in a class outside from the controller?
$event = $this->getDoctrine()
->getRepository('AtotrukisMainBundle:Event')
->findByCreatedBy($userId);
if (!$event) {
throw $this->createNotFoundException(
'You have no events'
);
}
The code above works perfectly in a controller, but in a service I get error: Attempted to call method "getDoctrine" on class "Atotrukis\MainBundle\Service\EventService" in /var/www/src/Atotrukis/MainBundle/Service/EventService.php line 15.
How do I make it work?
services.yml:
services:
eventService:
class: Atotrukis\MainBundle\Service\EventService
Part from the 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;
}
}
Upvotes: 0
Views: 198
Reputation: 9362
You can pass it as an argument in your service declaration:
services:
eventService:
class: Atotrukis\MainBundle\Service\EventService
arguments: ["@doctrine.orm.entity_manager"]
Then just add a constructor to your class:
protected $em;
public function __construct($em)
{
$this->em = $em
}
Upvotes: 2