0

As I understand the best code style is to put the complex SQL/DQL queries to the entity repositories.

For example there is an entity named "News". It has an own entity repository named "NewsRepository".

In the controller there is this code:

/**
 * @Route("/news", name="news")
 */
public function indexAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $paginator = $this->get('knp_paginator');

    $news = $paginator->paginate(
        $em->createQuery('SELECT n FROM AppBundle:News n'),
        $request->query->getInt('page', 1),
        10
    );

    return $this->render('app/news/list.html.twig', array(
        'news' => $news,
    ));
}

Now I like to add further features (filtering, order by, ..). That because I think the query should be moved to any service or the entity repository. But how and what is the best coding style?

(And does anybody have nice generic ideas how to easily add filtering, order by ... ?)

4

2 回答 2

1

当然,

如果您想再次使用它,每个请求都应该在存储库中。不仅最复杂。

我会尝试回答你的第一个问题,然后给你一个可以帮助你“通用过滤”的提示

如果您想将您的请求放入仓库,只需在您的 NewsRepository 中进行:

public function findAllOrderedByDate() {
    $qb = $this->createQueryBuilder('n');
    $qb->orderBy('creationDate');

    return $qb->getQuery()->getResult();
}

在你的控制器中:

public function indexAction(Request $request)
{
    $newsRepo = $this->get('doctrine')->getRepository('AppBundle:News');
    $em = $this->getDoctrine()->getManager();
    $paginator = $this->get('knp_paginator');

    $news = $newsRepo->findAllOrderedByDate();
    $pagination = $paginator->paginate(
        $news,
        $request->query->getInt('page', 1),
        10
    );

    return $this->render('app/news/list.html.twig', array(
        'news' => $pagination,
    ));
}

对于过滤,您的报告中有一个技巧,即返回 qb 而不是直接结果。

同样,您可以创建一个函数,使用给定参数(使用addOrderBy()or andWhere)添加您的 orderBy 并返回 queryBuilder。毕竟,你可以处理。

编辑 :


我在此线程上阅读的解决方案:

public function findAllOrderedByDate(callable $func = null) {
    $qb = $this->createQueryBuilder('n');
    $qb->orderBy('creationDate');

    if (is_callable($func)) {
        return $func($qb);
    }
    return $qb->getQuery()->getResult();
}

在你的控制器中:

$func = function (QueryBuilder $qb) use ($paginator, $request) {
    return $paginator->paginate($qb, $request->query->getInt('page', 1), 10);
};
$pagination = $em->getRepository('AppBundle:News')->findAllOrderedByDate($func);
于 2015-11-30T08:38:13.940 回答
0

模型零件必须在模型零件中。将查询移至仓库。你是什​​么意思,这样说:“如何轻松添加过滤,排序的好通用想法”?
OrderBy
Where - 相同的链接

于 2015-11-30T08:14:37.590 回答