Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在服务中使用条令Symfony2_Symfony_Doctrine Orm - Fatal编程技术网

在服务中使用条令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
}