How to use KNPPaginatorBundle to paginate results using Doctrine Repository?

后端 未结 3 1416
梦如初夏
梦如初夏 2021-02-05 23:46

I\'m working on a Symfony2 project and I decided to use KNPPaginatorBundle to build an easy pagination system. So I created a Product entity and I want to add the paginator to i

3条回答
  •  不知归路
    2021-02-06 00:10

    I think in some cases we could use Closure and pass to it a QueryBuilder object.

    In your ProductRepository you could do something like this:

    ProductRepository extends EntityRepository
    {
        public function findAllPublished(callable $func = null)
        {
            $qb = $this->createQueryBuilder('p');
    
            $qb->where('p.published = 1');
    
            if (is_callable($func)) {
                return $func($qb);
            }
    
            return $qb->getQuery()->getResult();
        }
    }
    

    and then in ProductController:

    public function indexAction(Request $request)
    {
        $em = $this->get('doctrine.orm.entity_manager');
        $paginator = $this->get('knp_paginator');
    
        $func = function (QueryBuilder $qb) use ($paginator, $request) {
            return $paginator->paginate($qb, $request->query->getInt('page', 1), 10);
        };
        $pagination = $em->getRepository('AppBundle:Report')->findAllPublished($func);
    
        // ...
    }
    

    I think it more flexible and you could use findAllPublished method to get both paginated or NOT paginated results if you need.

    Also keep in mind that callable type hint work in PHP >=5.4! Please, check docs for more info.

提交回复
热议问题