在twig中使用存储库类方法

时间:2013-01-20 14:50:20

标签: symfony doctrine-orm twig symfony-2.1

在Symfony2.1项目中,如何在模板中调用自定义实体函数?详细说明,请考虑以下场景;有两个具有多对多关系的实体:用户和类别。

Doctrine2已经生成了这样的方法:

$user->getCategories();
$category->getUsers();

因此,我可以在树枝中使用这些:

{% for category in categories %}
   <h2>{{ category.name }}</h2>
   {% for user in category.users %}
      {{ user.name }}
   {% endfor %}
{% endfor %}

但是如何让用户获得自定义功能呢?例如,我想列出具有一些选项的用户,并按日期排序,如下所示:

{% for user in category.verifiedUsersSortedByDate %}

我在UserRepository.php类中编写了自定义函数,并尝试将其添加到Category.php类中以使其工作。但是我收到了以下错误:

  

渲染过程中抛出异常   一个模板(“警告:缺少参数1 for   教义\ ORM \ EntityRepository :: __构建体(),

2 个答案:

答案 0 :(得分:3)

直接在控制器中检索verifiedUsersSortedByDate然后将其传递给模板会更加清晰。

//...
 $verifiedUsersSortedByDate = $this->getYourManager()->getVerifiedUsersSortedByDate();

return $this->render(
    'Xxx:xxx.xxx.html.twig',
    array('verifiedUsersSortedByDate' => $verifiedUsersSortedByDate)
);

你应该非常小心,不要在你的实体中做额外的工作。正如文档中所引用的那样,“实体是保存数据的基本类”。保持实体中的工作尽可能基本,并应用entityManagers中的所有“逻辑”。

如果您不想迷失在您的代码中,最好按顺序遵循这种格式(从实体到模板)

1 - Entity. (Holds the data)

2 - Entity Repositories. (Retrieve data from database, queries, etc...)

3 - Entity Managers (Perform crucial operations where you can use some functions from your repositories as well as other services.....All the logic is in here! So that's how we can judge if an application id good or not)

4 - Controller(takes request, return responses by most of the time rendering a template)

5 - Template (render only!)

答案 1 :(得分:0)

您需要通过存储库

获取控制器内的用户
$em = $this->getDoctrine()->getEntityManager();
$verifiedusers = $em->getRepository('MYBundle:User')->getVerifiedUsers();

 return array(
            'verifiedusers'      => $verifiedusers,
                   );
    }
相关问题