如何从AJAX调用的eventlistener获取用户ID [英] How to get userid from eventlistener which are called from AJAX

查看:66
本文介绍了如何从AJAX调用的eventlistener获取用户ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用symfony2和FOSUserBundle.

I am using symfony2 and FOSUserBundle.

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

Normally,I can get user data from Controller

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

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

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

But now,I want to get the userdata from eventlistner which are called from Ajax.

有可能吗?还是不?

我的消息来源在这里.

    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的建议.

according to @nifr's advice.

我在源代码线中做了一些改动,例如

I changed a bit in my source cord like

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进行侦听. 如何在此添加第二个参数?

then I want to pass the second argument to eventlistner. I am using services.xml to make listener. How can I add second argument on this?

 <?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>

推荐答案

您需要通过依赖项注入到您的侦听器类中以进行访问.

You need to inject the container via Dependency Injection into your listener class in order to acccess it.

书籍章节中了解有关此内容的更多信息.

Read more about it in the book chapter.

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

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

Though injecting the whole container is performance-wise not the best idea among with some other reasons like testability ( you should normally only inject the services you need in your class instead of the container )...

...如果您不使用UserCallable,则在注入@security.context时会得到循环引用.

...in your case if you aren't using a UserCallable you will get a circular reference when injecting @security.context.

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

So the quickest solution is injecting the container and adjusting your listener's constructor:

private $container;

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



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

    // ...
}

这篇关于如何从AJAX调用的eventlistener获取用户ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆