I have a question about Symfony2 Controller extending. For the moment, I was always extending the FrameworkBundle one for every controller in my app. But I'm getting sick of always retrieving the user by making a
$this->get('security.context')->getToken()->getUser()
or a
$this->getDoctrine()->getEntityManager()
each time I need the user or the entity manager (I need them a lot). I wanted to be able to retrieve them just by doing $this->em and $this->user. So I decided to create a bundle named MyApp/RootBundle, which contains a new controller extending the FrameworkBundle one. This controller would be extended by every other controller in the app. Here is the code :
<?php
namespace MyApp\RootBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface;
class RootController extends Controller
{
protected $em;
protected $user;
public function setContainer(ContainerInterface $container = null)
{
parent::setContainer($container);
$this->onContainerSet();
}
public function onContainerSet()
{
$this->em = $this->getDoctrine()->getEntityManager();
$this->user = $this->get('security.context')->getToken()->getUser();
}
}
I couldn't load the $this->em and $this->user in a __construct() function since the container is not loaded at the construction time.
So my questions are :
- Is that a good idea or should I continue to make the verbose calls ?
- Would it be better to just create functions getEm() and getUser() that would do the same job ?
Thanks !