Symfony2修改全局用户引用?

时间:2015-01-14 19:51:49

标签: php symfony

我的User类中有函数setAttribute($ key,$ value)和getAttribute($ key,$ default)。当用户通过身份验证时,我想设置几个要设置的属性,稍后将在各种控制器中使用。

我尝试在成功处理函数中设置属性:

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
      $token->getUser()->setAttribute("user_data_set", 1);
 }

但是当我尝试在我的控制器中调用它时,值尚未设置

public function indexAction(Request $request) {

    //Get the logged in user
    $user = $this->getUser(); 
    //Entity Manager
    $em = $this->getDoctrine()->getManager();

    // this page is just used as the starting point to redirect the user to the appropriate page
    if($user->getAttribute("user_data_set", 0) == 1)
    {
        //Get Symfony1 route from the user data table
        $old_homepage = $user->getAttribute("user_homepage", "@default_homepage");
        //Convert route to Symfony2 format
        $new_homepage = $this->setForwardingAddress($old_homepage);

        return $this->redirect($this->generateUrl($new_homepage));
    }
    else
    {
        return $this->redirect('login');
    }        


}

如何修改全局用户而不是本地引用?

1 个答案:

答案 0 :(得分:1)

您显然需要交叉请求解决方案,因此您需要使用DBsession

例如:

// Injecting Session service
public function __construct(Session $session){
    $this->session = $session
}

public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $this->session->set('user_data_set', 1);
}

然后在你的控制器中:

$foo = $session->get('user_data_set');

这是你想要的吗?