8

我正在使用 symfony2 和 FOSUserBundle。

通常,我可以从 Controller 获取用户数据

$user = $this->get('security.context')->getToken()->getUser();

或者

$user = $this->container->get('security.context')->getToken()->getUser(); 

但是现在,我想从 Ajax 调用的 eventlistner 获取用户数据。

是否可以?或不?

我的来源在这里。

    namespace Acme\MemberBundle\EventListener;

    use ADesigns\CalendarBundle\Event\CalendarEvent;
    use ADesigns\CalendarBundle\Entity\EventEntity;
    use Doctrine\ORM\EntityManager;

    class CalendarEventListener
    {
        private $entityManager;

        public function __construct(EntityManager $entityManager)
        {
            $this->entityManager = $entityManager;
        }

        public function loadEvents(CalendarEvent $calendarEvent)
        {
            $startDate = $calendarEvent->getStartDatetime();
            $endDate = $calendarEvent->getEndDatetime();


           $user = $this->container->get('security.context')->getToken()->getUser();//it doesnt work

            // load events using your custom logic here,
            // for instance, retrieving events from a repository

            $companyEvents = $this->entityManager->getRepository('UserBundle:MutorSche')
                    ->createQueryBuilder('company_events')
                    ->where('company_events.event_datetime BETWEEN :startDate and :endDate')
                    ->setParameter('startDate', $startDate->format('Y-m-d H:i:s'))
                    ->setParameter('endDate', $endDate->format('Y-m-d H:i:s'))
                    ->getQuery()->getResults();



            foreach($companyEvents as $companyEvent) {

                // create an event with a start/end time, or an all day event
                if ($companyEvent->getAllDayEvent() === false) {
                    $eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), $companyEvent->getEndDatetime());
                } else {
                    $eventEntity = new EventEntity($companyEvent->getTitle(), $companyEvent->getStartDatetime(), null, true);
                }

                //optional calendar event settings
                $eventEntity->setAllDay(true); // default is false, set to true if this is an all day event
                $eventEntity->setBgColor('#FF0000'); //set the background color of the event's label
                $eventEntity->setFgColor('#FFFFFF'); //set the foreground color of the event's label
                $eventEntity->setUrl('http://www.google.com'); // url to send user to when event label is clicked
                $eventEntity->setCssClass('my-custom-class'); // a custom class you may want to apply to event labels

                //finally, add the event to the CalendarEvent for displaying on the calendar
                $calendarEvent->addEvent($eventEntity);
            }
        }
    }

根据@nifr 的建议。

我在源代码中做了一些改变,比如

class CalendarEventListener
{
    private $entityManager;
    private $container;//add

    public function __construct(
            EntityManager $entityManager,
            ContainerInterface $container)//add
    {
        $this->entityManager = $entityManager;
        $this->container = $container;//add
    }

然后我想将第二个参数传递给 eventlistner。我正在使用 services.xml 来制作监听器。我该如何添加第二个论点?

 <?xml version="1.0" encoding="UTF-8" ?>
      <container xmlns="http://symfony.com/schema/dic/services">

        <services>
            <service id="acme.memberbundle.calendar_listener" class="Acme\MemberBundle\EventListener\CalendarEventListener">
                <argument type="service" id="doctrine.orm.entity_manager" />
                <tag name="kernel.event_listener" event="calendar.load_events" method="loadEvents" />
            </service>

        </services>
      </container>
4

3 回答 3

17

从 Symfony 2.6 开始,这个问题应该得到修复。一个拉取请求刚刚被主服务器接受。您的问题在此处描述。 https://github.com/symfony/symfony/pull/11690

从 Symfony 2.6 开始,您可以将 注入security.token_storage到您的侦听器中。该服务将包含SecurityContext<=2.5 中使用的令牌。在 3.0 中,此服务将SecurityContext::getToken()完全取代。您可以在此处查看基本更改列表:http: //symfony.com/blog/new-in-symfony-2-6-security-component-improvements#deprecated-the-security-context-service

2.6 中的示例用法:

你的配置:

services:
    my.listener:
        class: EntityListener
        arguments:
            - "@security.token_storage"
        tags:
            - { name: doctrine.event_listener, event: prePersist }


你的听众

use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class EntityListener
{
    private $token_storage;

    public function __construct(TokenStorageInterface $token_storage)
    {
        $this->token_storage = $token_storage;
    }

    public function prePersist(LifeCycleEventArgs $args)
    {
        $entity = $args->getEntity();
        $entity->setCreatedBy($this->token_storage->getToken()->getUsername());
    }
}
于 2014-09-24T08:17:35.363 回答
5

您需要通过依赖注入将容器注入到您的侦听器类中才能访问它。

在本书章节中阅读更多相关信息。

your.listener:
    class: Acme\MemberBundle\EventListener\CalendarEventListener
    arguments: ["@service_container"]

尽管注入整个容器在性能方面并不是最好的主意,但还有其他一些原因,例如可测试性(您通常应该只在类中注入您需要的服务而不是容器)......

...在您的情况下,如果您不使用 UserCallable 您将在注入时获得循环引用@security.context

因此,最快的解决方案是注入容器并调整侦听器的构造函数:

private $container;

public function __construct(ContainerInterface $container)
{
    $this->container = $container;
}



public function someOtherMethod()
{
    $user = $this->container->get('security.context')->getToken()->getUser();

    // ...
}
于 2013-06-10T11:00:44.780 回答
5

确保没有Symfony profiler/toolbar打开。我不知道为什么,但每次都会$this->container->get('security.context')->getToken()返回。null

在文件中,config_dev.yml确保设置了以下内容:

web_profiler:
  toolbar: false
于 2015-05-01T19:58:15.187 回答