完全工作的示例在这里->
使用Doctrine查询构建器中的限制和偏移量进行手动分页。我只是给你需要先了解的代码。
这就是它的工作原理,对我来说这是最佳实践!也许并不适用于其他人!
1.请求发送到控制器
2.控制器调用服务
3.服务使用Trait规范化请求参数
4.服务从仓库中提取数据
5.仓库将结果返回给服务
6.服务将结果传递给工厂
7.工厂创建结果模型
8.工厂将结果模型返回给服务
9.服务将结果模型返回给控制器
仓库(REPO)
namespace Application\BackendBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
class StudentRepository extends EntityRepository
{
public function findPaginatedByName($name, $limit, $offset)
{
$qb = $this->createQueryBuilder('s');
if ($name) {
$qb->where('s.name = :name')->setParameter('name', $name);
}
$qb->setMaxResults($limit)->setFirstResult($offset);
return $qb->getQuery()->getResult(Query::HYDRATE_SIMPLEOBJECT);
}
public function findPaginatedByNameCount($name)
{
$qb = $this->createQueryBuilder('s')->select('COUNT(s)');
if ($name) {
$qb->where('s.name = :name')->setParameter('name', $name);
}
return $qb->getQuery()->getResult(Query::HYDRATE_SINGLE_SCALAR);
}
}
PAGER TRAIT
namespace Application\BackendBundle\Util;
trait PagerTrait
{
public function getPage($page = 1)
{
if ($page < 1) {
$page = 1;
}
return floor($page);
}
public function getLimit($limit = 20)
{
if ($limit < 1 || $limit > 20) {
$limit = 20;
}
return floor($limit);
}
public function getOffset($page, $limit)
{
$offset = 0;
if ($page != 0 && $page != 1) {
$offset = ($page - 1) * $limit;
}
return $offset;
}
}
服务
namespace Application\BackendBundle\Service;
use Application\BackendBundle\Factory\StudentFactoryInterface;
use Application\BackendBundle\Model\Student\Result;
use Application\BackendBundle\Repository\StudentRepository;
use Application\BackendBundle\Util\PagerTrait;
class StudentService implements StudentServiceInterface
{
use PagerTrait;
private $studentRepository;
private $studentFactory;
public function __construct(
StudentRepository $studentRepository,
StudentFactoryInterface $studentFactory
) {
$this->studentRepository = $studentRepository;
$this->studentFactory = $studentFactory;
}
public function get($name, $page, $limit)
{
$page = $this->getPage($page);
$limit = $this->getLimit($limit);
$offset = $this->getOffset($page, $limit);
$total = 0;
$result = $this->studentRepository->findPaginatedByName($name, $limit, $offset);
if ($result) {
$total = $this->studentRepository->findPaginatedByNameCount($name);
}
return $this->studentFactory->createStudentResult($result, $name, $page, $limit, $total);
}
}
($page-1) * 100;
,其中 $page 是所请求的页码,并将其替换为 setFirstResult 中的 0。此外,没有必要两次执行 getQuery / getResult。只需删除您那里的前两个调用即可。 - JimL