symfony 2.3 Call to a member function get() on a non-object in __construct function

770 views Asked by At

My project runs on symfony 2.3 with fosuserbundle. I want to get the current user in the controller

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

and it works if I do it in indexAction(). But i need the user in every function of the controller so I tried putting the code in a __construct function and now it doesn't work anymore.

Why can't I set the variable in a construct function?

1

There are 1 answers

0
Senthil Kumar On

Inside the construct function use:

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

Do not use:

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

So it should like this:

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

     }

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

      }
   }