完全工作示例在这里 -> Using limit and offset in doctrine query builder for manual pagination。我只是给你一些你需要先理解的代码。
这就是它的工作原理,对我来说这是最好的做法!也许不适合其他人!
- 请求转到控制器
- 控制器调用服务
- 具有特征的服务规范化请求参数
- 服务从存储库中提取数据
- 存储库将结果返回给服务
- 服务将结果传递给工厂
- 工厂创建结果模型
- 工厂将结果模型返回给服务
- 服务将结果模型返回给控制器
回购
namespace Application\BackendBundle\Repository;
use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\Query;
class StudentRepository extends EntityRepository
{
/**
* @param string|null $name
* @param int $limit
* @param int $offset
*
* @returns array
*/
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);
}
/**
* @param string|null $name
*
* @return int
*/
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);
}
}
寻呼机特征
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;
}
/**
* @param string $name
* @param int $page
* @param int $limit
*
* @return Result
*/
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);
}
}