【问题标题】:symfony 2.3 Call to a member function get() on a non-object in __construct functionsymfony 2.3 在 __construct 函数中调用非对象的成员函数 get()
【发布时间】:2013-12-18 19:25:07
【问题描述】:

我的项目在带有 fosuserbundle 的 symfony 2.3 上运行。 我想在控制器中获取当前用户

$securityContext = $this->get('security.context');
$this->currentUser = $securityContext->getToken()->getUser();

如果我在indexAction() 中这样做,它就会起作用。 但是我在控制器的每个功能中都需要用户,所以我尝试将代码放在 __construct 函数中,现在它不再起作用了。

为什么我不能在构造函数中设置变量?

【问题讨论】:

  • $this->getUser() 就是你所需要的。看一下 S2 基础控制器类。您会注意到它没有构造函数,并且稍后会使用 setContainer 方法注入容器。这就解释了为什么将这种代码放在构造函数中不起作用。但同样,现有的 getUser 方法意味着您无论如何都不需要使用 consturcor,
  • 哦,我明白了。感谢您的快速答复!

标签: php symfony fosuserbundle security-context


【解决方案1】:

在构造函数内部使用:

return $this->redirect('login');

不要使用:

   return $this->redirect($this->generateUrl('login'));

所以应该是这样的:

   class DefaultController extends Controller
   {
     public function __construct()
     {
           return $this->redirect('login');
           exit;

     }

      /**
      * @Route("/", name="home")
      */
     public function indexAction(Request $request)
      {

      }
   }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    相关资源
    最近更新 更多