如何在循环中访问特定方法?

时间:2012-10-19 14:54:23

标签: php model-view-controller symfony tree twig

假设我有一个Category实体,一个Person实体,这两个实体与一个合同实体相关联。
在我看来,我需要显示一个包含所有子类别和人数的类别

例如: 当用户在页面上查看“A类”时,我希望他/她看到:

Category A                  10 persons
  subcategory a.1            4 persons
  subcategory a.2            6 persons

所以在我的show.html.twig中,我会写:

{{ category.title }}  {{ nb_persons }}
{% for child in children %}
   {{ child.title }} //{{ child.getNbPersons() }}??, how to get the number of persons for each child ?
{% endfor %}

这是我的CategoryController.php

public function showAction($id_category)
{
    $em=$this->getDoctrine()->getEntityManager();
    $repo = $em->getRepository('MyBundle:Category');
    $this->param['category']= $repo->find($id);
    $this->param['nb_persons'] = $repo->getNbPersonsByCategory($id_category);
    $this->param['children'] = $repo->children($this->param['category'], true, 'title');

return $this->render('MyBundle:Category:show.html.twig', $this->param);
}

但要显示每个子类别(子)的人数,我需要使用像child.getNbPersons()这样的方法,但这会迫使我在我的实体Category.php中使用存储库函数,这是一个坏的我想是练习。 我能做什么 ?

1 个答案:

答案 0 :(得分:1)

我倾向于完全将模型与其他一切隔离开来。也就是说,模型不知道控制器,存储库等。

关于你的问题,我宁愿在控制器中构建一个合适的对象(以及array),并将其原样传递给Twig,并且array应该包含所有预先计算的信息。这样,如果你有很多类别(和/或子类别),你只需要执行一次数据库查询,而不是从模型方法调用存储库,其中每个调用都需要一个查询。

希望这有助于......;)