2012-10-05 10 views
7

私の問題は、ユーザのログアウトをキャプチャすることです。私が持っているもののコードは次のとおりです。symfony2ログアウト

public function onAuthenticationFailure(Request $request, AuthenticationException $exception){ 

    return new Response($this->translator->trans($exception->getMessage())); 
} 

public function logout(Request $request, Response $response, TokenInterface $token) 
{ 
    $empleado = $token->getUser(); 
    $log = new Log(); 
    $log->setFechalog(new \DateTime('now')); 
    $log->setTipo("Out"); 
    $log->setEntidad(""); 
    $log->setEmpleado($empleado); 
    $this->em->persist($log); 
    $this->em->flush(); 
} 

public function onLogoutSuccess(Request $request) { 
    return new RedirectResponse($this->router->generate('login')); 
} 

問題は、ログアウト機能を実行しているとき、私はTokenInterfaceトークンユーザーにアクセスすることはできませんでしょうか?

+1

soluctionの問題は、サービスのセキュリティコンテキストでありますありがとう。 – paradita

+1

'$ token-> getUser()'はnullを返しますか?あるいは、 '$ token'がヌルですか? – Kosta

答えて

11

トークンを取得するには、セキュリティコンテキストを注入する必要があります。

1.、このような何かクラスログアウトリスナーを作成しますが、

.... 
logout_listener: 
    class: Yourproject\Yourbundle\Services\LogoutListener 
    arguments: [@security.context] 

それだ:この行を追加し、service.ymlで

namespace Yourproject\Yourbundle\Services; 
... 
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface; 
use Symfony\Component\Security\Core\SecurityContext; 

class LogoutListener implements LogoutSuccessHandlerInterface { 

    private $security; 

    public function __construct(SecurityContext $security) { 
    $this->security = $security; 
    } 

    public function onLogoutSuccess(Request $request) { 
    $user = $this->security->getToken()->getUser(); 

    //add code to handle $user here 
    //... 

    $response = RedirectResponse($this->router->generate('login')); 

    return $response; 
    } 
} 

2.その後を助けになる。

+2

これは機能しません。logout_listenerサービスの場合、定義されたイベントはありません。だから、リスナーはまったく解雇されません。 –

+0

@artworkadシ、私はこのイベントをservice.ymlに登録しているので、ユーザーがログアウトすると解雇されます。私はこれをいくつかのプロジェクト交響曲で使用しましたが、問題はありません。 – tesmojones

+1

私の意見では、7月24日14:15:22に回答の行を追加する必要があります。これはsymfony 2.5で私のために働いていました。 – ziiweb