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 indexAction action (generated by CRUD command).
// Retrieving products.
$em = $this->getDoctrine()->getManager();
//$entities = $em->getRepository('LiveDataShopBundle:Product')->findAll();
$dql = "SELECT a FROM LiveDataShopBundle:Product a";
$entities = $em->createQuery($dql);
// Creating pagnination
$paginator = $this->get('knp_paginator');
$pagination = $paginator->paginate(
$entities,
$this->get('request')->query->get('page', 1),
20
);
It works fine but I want to use the Product's repository instead of creating the query directly in the controller. How can I do that ? In fact, directly add the collection of results to the paginate object is just too slow because its load all products then paginate the ArrayCollection.
Thanks in advance.
K4
I think in some cases we could use
Closure
and pass to it aQueryBuilder
object.In your
ProductRepository
you could do something like this:and then in
ProductController
: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.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:
And here is the important code in my repository:
I suggest using
QueryBuilder
in yourProductRepository
and then passing that to the paginator:In the controller: