How to use KNPPaginatorBundle to paginate results using Doctrine Repository?

后端 未结 3 1421
梦如初夏
梦如初夏 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:01

    In our project we want to avoid using Doctrine queries in controllers. We have also separate layers. Controllers must not access the database. So I included pagination in the Repository.

    Here my code in controller:

    public function indexAction(Request $request)
    {
        $userRepository = $this->get('user_repository');
        $page = intval($request->query->get('page', 1));
        $pages = 0;
        $users = $userRepository->findAllPaginated($pages, $page - 1, 10);
    
        return $this->render('User:index.html.twig', array(
            'users' => $users,
            'page' => $page,
            'pages' => $pages,
        ));
    }
    

    And here is the important code in my repository:

    use Doctrine\ORM\Tools\Pagination\Paginator;
    class UserRepository extends EntityRepository
    {
        /**
         * @return User[]
         */
        public function findAllPaginated(&$pages, $startPage = 0, $resultsPerPage = 5)
        {
            $dql = 'SELECT u FROM CoreBundle:User u';
            $query = $this->getEntityManager()->createQuery($dql)
                ->setFirstResult($startPage * $resultsPerPage)
                ->setMaxResults($resultsPerPage);
    
            $paginator = new Paginator($query);
            $count = $paginator->count();
            $pages = floor($count/$resultsPerPage);
    
            return $paginator; // on $paginator you can use "foreach", so we can say return value is an array of User
        }
    }
    

提交回复
热议问题