doufu2496
2016-10-05 10:30
浏览 117
已采纳

如何在twig扩展服务中获取当前用户[symfony2.8]

I'm trying to get the current user in my NotificationExtension.php. But the page become very slow to load and I also get this error:

Error: Call to a member function getUser() on null

The error say that is impossible to get the current user, but i'm login.

This is my service:

notification:
  class: Application\Sonata\UserBundle\Twig\NotificationExtension
  arguments: ['@doctrine.orm.entity_manager', '@service_container', '@security.context']
  tags:
        - { name: twig.extension }

NotificationExtension :

<?php

namespace Application\Sonata\UserBundle\Twig;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Twig_Extension;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Security;

class NotificationExtension extends \Twig_Extension
{
    protected $container;
    protected $em;

    public function __construct(EntityManager $em,ContainerInterface $container, SecurityContext $context)
    {
        $this->container = $container;
        $this->em = $em;
        $this->doctrine = $container->get('doctrine');
        $this->context = $context;
    }

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

        return(array(

            'unreadMessagesCount' => $this->em->getRepository('ApplicationSonataUserBundle:Notif')->findBy(
                    array(
                        'user' => $user,
                        'seen' => true
                    ),
                    array('date' => 'DESC')
                )));
    }

    public function getName()
    {
        return 'notification';
    }
}

ADD:

service:

notification:
  class: Application\Sonata\UserBundle\Twig\NotificationExtension
  arguments: ['@doctrine.orm.entity_manager','@security.token_storage']
  tags:
        - { name: twig.extension }

get current user:

public function getUser()
{
    return $this->tokenStorage->getToken()->getUser();
}
  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

2条回答 默认 最新

相关推荐 更多相似问题