I have a controller which has actions for inserting in the database, updating, deleting and some others, but almost all of the actions contain in them this lines:
$em = $this->getDoctrine()->getEntityManager();
$friend = $em->getRepository('EMMyFriendsBundle:Friend')->find($id);
$user = $this->get('security.context')->getToken()->getUser();
Is this OK, or it’s code duplication? I tried to make a property called $em and to have a constructor like this:
public function __construct()
{
$this->em = $this->getDoctrine()->getEntityManager();
}
but it didn’t work. As for the queries especially the one with the $id parameter, I don’t even know how to separate them in one place, so each action to be able to use them. One way is a function, but is there sense in a function like this? And if yes what should it return? An array?
Please advise me for the optimal way!
You can do:
Then you can call in your actions
or
And you will have
available. Note that I allowed for the $id parameter not to be set, as I guess that in some actions you will not have it.
If you want this init function to be available in different controllers, create a base controller and extend from it, as suggested in another answer.