简体   繁体   中英

Should I repack the fetched entity object before passing it to the twig template?

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?

Common practice is definitely to hand over your entity graph directly to the view.

Why do you think your second example is harder to read?

If you don't want those chained calls in the template you might want to consider adding another getter in your User entity. Something like:

public function getNamesOfFriendsGirlfriends() 
{
  $gfNames = [];
  foreach($this->getFriends() as $friend) {
    $gfNames[] = $friend->getGirlfriend()->getName();
  }
  return $gfNames;
}

And then call that in your template:

{% for gfName in user.namesOfFriendsGirlfriends %}
    {{ gfName }}
{% endfor %}

And if you need many of these helpers and don't want to spoil your nice and clean entities you might want to consider wrapping them in a Decorator object before using it in the view layer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM