I'm using Symfony 4. I have a fetched object $user that has relationships with other entities. I have setup all the getter so I can get other information from that $user object.
$user = $em->getDoctrine()->getRepository(User::class)->find($id);
$usergroup = $user->getGroup()->getName();
What I'll do is to create a new object for repacking the information I needs from the $user object before passing it to the template.
# controller
$repack_user = new \stdClass();
$repack_user->id = $user->getId();
$user_friends = $user->getFrends();
$friends_gf = [];
foreach($user_friends as $friend) {
$friends_gf[] = $friend->getGirlfriend()->getName();
}
$repack_user->friends_gf = $friends_gf;
return $this->render("home.html.twig", ['user' => $repack_user]);
And then in the template, I unpacked it with similar procedures.
# twig template
{{ user.id }}
{% for gf in user.friends_gf %}
{{ gf }}
{% endfor %}
But since I can also call entity function inside twig, I can skip all the whole repacking in the controller and pass the $user object right into the template.
# skipped repack in controller
# twig template
{{ user.getID() }}
{% for friend in user.getfriends %}
{{ friend.getGirlfriend().getName() }}
{% endfor %}
The first way is kind of redundant because I have to do it twice. The second way is kind of hard to read. So which one is the more reasonable approach? What is the common practice for this?