1

Let's say I have a Category entity, a Person entity, and these two are related by a Contract Entity.
In my view, I need to display a category with all its subcategories with the number of persons

For example : when the user is on the page to view "the category A", I would like he/she sees that :

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

So in my show.html.twig, I would write :

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

Here's my 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);
}

But to display the number of persons for each subcategory(child) I need to use a method like child.getNbPersons(), but this would force me to use a repository function in my entity Category.php and this is a bad practice I think. What can I do ?

Reveclair
  • 2,399
  • 7
  • 37
  • 59
  • I don't think entity repository methods are a bad practice. They are very useful for such situations. – vinnylinux Oct 19 '12 at 16:04
  • Thanks for your answer, so I need to access the container to get the entity manager in my entity Category.php, I tried this $em=$this->container->get('doctrine')->getEntityManager(); but the container seems not defined here.. How could I access it ? – Reveclair Oct 19 '12 at 16:12
  • http://stackoverflow.com/questions/4465237/doctrine2-best-practice-should-entities-use-services – vinnylinux Oct 19 '12 at 16:15

1 Answers1

1

I tend to totally isolate model from everything else. That is, model is not aware controller, repositories etc.

Regarding your problem I would rather construct an appropriate object (well an array) within controller and pass it to Twig as it is and that array should hold all the info needed precalculated. That way, if you have a lot of categories (and/or subcategories) you would have to exec database query only once, opposed to calling the repository from model method where each call would require a single query.

Hope this helps... ;)

Jovan Perovic
  • 19,846
  • 5
  • 44
  • 85