gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:56:48 25 4
gpt4 key购买 nike

我试图在我的 NotificationExtension.php 中获取当前的 user。但是页面加载速度变得非常慢,我也收到了这个错误:

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

错误说无法获取当前用户,但我正在登录。

这是我的服务:

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

通知扩展:

<?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';
}
}

添加:

服务:

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

获取当前用户:

public function getUser()
{
return $this->tokenStorage->getToken()->getUser();
}

最佳答案

将服务定义为全局 Twig 变量:

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

服务类:

// 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;
}
}

服务定义:

# app/config/config.yml

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

最后,对于您可以使用此服务的所有模板:

# foo.html.twig

{{ user_notification.unreadMessages|length }}

无论何时在模板中访问全局变量,都会从服务容器请求服务,并且您可以访问该对象。


更多信息 http://symfony.com/doc/current/templating/global_variables.html

关于php - 如何在twig扩展服务中获取当前用户[symfony2.8],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39871558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com