2016-10-05 10 views
3

私は現在userを私のNotificationExtension.phpに入れようとしています。しかし、非常に遅くなるページがロードすると私はまた、このエラーが出る:twig拡張サービスで現在のユーザを取得する方法[symfony2.8]

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 } 

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:

サービス:

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

現在のユーザーを取得:

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

サービス

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

@ security.token_storage' 'サービスを試してみて、アクセスユーザーとして:'ます$ this->ユーザー=($ tokenStorage->を入手トークン())? $ tokenStorage-> getToken() - > getUser():null; ' – Jeet

+0

あなたの行を' public function getGlobals() 'に置くと、次のエラーが出ます。 'Notice:Undefined variable:tokenStorage' – Sirius

+0

サービス定義とクラスで' $ tokenStorage'を使って 'SecurityContext $ context'を変更するつもりでした。 – Jeet

答えて

3

ではなく、グローバル小枝変数としてサービスを定義します。定義:

# 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

+0

ありがとうございました。しかし、userNotificationの '$ user = $ token-> getUser();'行と '$ unreadMessages;'は未定義です。 – Sirius

+0

はい、これらの行を入力する必要があります。ユーザーの問題を解決するためのヒントのみを示します。 – yceruto

+0

エンティティマネージャサービスを挿入してクエリを作成する必要があります; – yceruto

1

あなたはそのようなユーザー名をアクセスすることができます。app.user.username

あなたはユーザーがログインしているかどうかを確認したい場合は、is_granted小枝の機能を使用することができます。

例:

{% if is_granted("ROLE") %} 
    Hi {{ app.user.username }} 
{% endif %} 
関連する問題