简体   繁体   English

我应该在将获取的实体对象传递到树枝模板之前重新打包吗?

[英]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. 我正在使用Symfony4。我有一个已获取的对象$ user与其他实体有关系。 I have setup all the getter so I can get other information from that $user object. 我已经设置了所有的吸气剂,所以我可以从该$ user对象中获取其他信息。

$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. 我要做的是创建一个新对象,用于将$ user对象中需要的信息重新打包后再传递给模板。

# 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. 但是由于我也可以在树枝中调用实体函数,因此可以跳过控制器中的所有重新打包过程,并将$ user对象直接传递到模板中。

# 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. 如果您不希望模板中的那些链式调用,则可以考虑在您的User实体中添加另一个getter。 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. 而且,如果您需要许多此类帮助器,并且不想破坏漂亮干净的实体,则可以在将其用于视图层之前考虑将其包装在Decorator对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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