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条回答 默认 最新

  • dongyi1215 2016-10-05 14:40
    关注

    Define instead a service as a global Twig variable:

    # app/config/config.yml
    twig:
        # ...
        globals:
            user_notification: '@app.user_notification'
    

    The service class:

    // src/AppBundle/Twig/Globals/UserNotification.php
    
    class UserNotification
    {
        private $tokenStorage;
        // ...
    
        public function __construct(TokenStorageInterface $tokenStorage, ...)
        {
            $this->tokenStorage = $tokenStorage;
            // ...
        }
    
        public function getUnreadMessages()
        {
            if (null === $token = $this->tokenStorage->getToken()) {
                return array();
            }
    
            $user = $token->getUser();
    
            // $unreadMessages = <DB query for get the unread messages from current user>
    
            return $unreadMessages;
        }
    }
    

    The service definition:

    # app/config/config.yml
    
    services:
        app.user_notification:
            class: AppBundle\Twig\Globals\UserNotification
            arguments: ['@security.token_storage', ...]
    

    Finally, for all templates you can to use this service:

    # foo.html.twig
    
    {{ user_notification.unreadMessages|length }}
    

    Whenever the global variable is accessed in the template, the service will be requested from the service container and you get access to that object.


    More information http://symfony.com/doc/current/templating/global_variables.html

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于#linux#的问题(输入输出错误):出现这个界面接着我重新装系统,又让修电脑的师傅帮我扫描硬盘(没有问题)用着用着又卡死(相关搜索:固态硬盘)
  • ¥15 cv::resize不同线程时间不同
  • ¥15 web课程,怎么做啊😭没好好听课 根本不知道怎么下手
  • ¥15 做一个关于单片机的比较难的代码,然后搞一个PPT进行解释
  • ¥15 python提取.csv文件中的链接会经常出现爬取失败
  • ¥15 数据结构中的数组地址问题
  • ¥15 maya的mel里,怎样先选择模型A,然后利用mel脚本自动选择有相同名字的模型B呢。
  • ¥15 Python题,根本不会啊
  • ¥15 会会信号与系统和python的来
  • ¥15 关于#python#的问题