【问题标题】:Using repository class methods inside twig在 twig 中使用存储库类方法
【发布时间】:2014-01-04 14:56:52
【问题描述】:

在 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 Doctrine\ORM\EntityRepository::__construct(),

【问题讨论】:

    标签: symfony doctrine-orm twig symfony-2.1


    【解决方案1】:

    直接在控制器中检索您的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!)
    

    【讨论】:

    • 其实你的逻辑是错误的。实体——是——唯一应该包含逻辑的地方。如果您要将逻辑放入控制器中,您将看到大量重复的大杂乱代码。
    • 感谢您的评论@Zelijko。我从来没有说过控制器......实体只保存元数据。引用文档“它是一个保存数据的基本类”。您需要使用实体管理器来处理这些数据,并在那里应用业务逻辑。我给你的观点是,其集合中的术语逻辑是指允许处理数据的实体+实体管理器+服务。我已经澄清了我的回答。谢谢。
    【解决方案2】:

    您需要通过存储库获取控制器中的用户

    $em = $this->getDoctrine()->getEntityManager();
    $verifiedusers = $em->getRepository('MYBundle:User')->getVerifiedUsers();
    

     return array(
                'verifiedusers'      => $verifiedusers,
                       );
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-09
      • 2012-11-28
      • 2022-11-16
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 2013-03-19
      相关资源
      最近更新 更多