I am having some trouble with Symfony2. Namely in how to use the __construct() function. the Official Documentation is shockingly bad!
I want to be able to use the following:
public function __construct()
{
parent::__construct();
$user = $this->get('security.context')->getToken()->getUser();
}
How ever I get the following error:
Fatal error: Cannot call constructor in /Sites/src/DEMO/DemoBundle/Controller/Frontend/HomeController.php on line 11
Line 11 is parent::__construct();. I removed it and got the following, new error
Fatal error: Call to a member function get() on a non-object in /Sites/vendor/symfony/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php on line 242
I think I might need to set up the ContainerInterface DIC, but I have no idea how to do this (I tried and failed, miserably)
Any ideas folks?
This is actually quite a common misconception for new S2 developers. As @KingCrunch says, the S2 controller has no construct and thus your approach will fail. Take a look at the source code: namespace Symfony\Bundle\FrameworkBundle\Controller\Controller and you will see that the Controller extends component ContainerAware which has one method called setContainer. If you really wanted to, you could override this method and do what you want.
However, there is an event system specifically designed for these sorts of things i.e. executing certain methods before the action method gets kicked off. Might want to search a bit for other questions on this topic.
The S2.1 controller now has a getUser() method. I’d suggest adding it to your base controller class and not worrying about it.