Мне нужно создать метод API с нумерацией страниц, и я создаю действие и службу, но у меня есть ответ:
{
"self_page": "\\/app_dev.php\\/projects?count=10&page=1&sort_by=created&sort_order=DESC",
"next_page": "\\/app_dev.php\\/projects?count=10&page=2",
"prev_page": "\\/app_dev.php\\/projects?count=10&page=0",
"first_page": "\\/app_dev.php\\/projects?count=10&page=1",
"last_page": "\\/app_dev.php\\/projects?count=10&page=10",
"projects": [
{
и все данные, у меня есть 100 строк в БД, затем в заголовке он отображается правильно, но почему бы не работать разбиение на страницы, я должен получить 10 строк, но у меня есть все (100 проектов), я создаю createQueryBuilder, и если я отлаживаю в $ queryBuilder, у меня есть правильный параметр ( coutn 4 -> у меня 4 проекта) но как этот параметр использовать в нумерации страниц
* RestView()
*
* @QueryParam(name="status", strict=true, requirements="[a-z]+", description="status of project", nullable=true)
* @QueryParam(name="count", requirements="\d+", default="10", description="Count project at one page")
* @QueryParam(name="page", requirements="\d+", default="1", description="Number of page to be shown")
* @QueryParam(name="sort_by", strict=true, requirements="^[a-zA-Z]+", default="created", description="Sort by", nullable=true)
* @QueryParam(name="sort_order", strict=true, requirements="^[a-zA-Z]+", default="DESC", description="Sort order", nullable=true)
*
* @param ParamFetcher $paramFetcher
* @return View
*
* @throws NotFoundHttpException when not exist
*/
public function getProjectsAction(ParamFetcher $paramFetcher)
{
$manager = $this->getDoctrine()->getManager();
$repository = $manager->getRepository('ArtelProfileBundle:Project');
if (!$paramFetcher->get('status')) {
$queryBuilder = $repository->createQueryBuilder('project')
->where('project.currentStatus != :identifier1','project.currentStatus != :identifier2')
->setParameter('identifier1', 'fail')
->setParameter('identifier2', 'rejected')
->orderBy('project.'.$paramFetcher->get('sort_by'), $paramFetcher->get('sort_order'))
->setFirstResult($paramFetcher->get('count') * ($paramFetcher->get('page') - 1))
->setMaxResults($paramFetcher->get('count'))
->getQuery()
->getResult()
;
} else {
$queryBuilder = $repository->createQueryBuilder('project')
->where('project.currentStatus = :identifier')
->setParameter('identifier', $paramFetcher->get('status'))
->orderBy('project.'.$paramFetcher->get('sort_by'), $paramFetcher->get('sort_order'))
->setFirstResult($paramFetcher->get('count') * ($paramFetcher->get('page') - 1))
->setMaxResults($paramFetcher->get('count'))
->getQuery()
->getResult()
;
}
$projectAll = $repository->findAll();
$paginator = $this->get('paginator');
$pagination = $paginator->getPaginated(
$paramFetcher->get('count'),
$paramFetcher->get('page'),
$paramFetcher->get('sort_by'),
$paramFetcher->get('sort_order'),
$projectAll
);
$projectResponse = new ProjectResponse();
$projectResponse->setProjects($projectAll);
$projectResponse->setSelfPage($pagination->getSelfPage());
$projectResponse->setNextPage($pagination->getNextPage());
$projectResponse->setPrevPage($pagination->getPrevPage());
$projectResponse->setFirstPage($pagination->getFirstPage());
$projectResponse->setLastPage($pagination->getLastPage());
return $projectResponse;
}
и создать службу нумерации страниц:
class PaginatorService
{
public function __construct(Router $router)
{
$this->router = $router;
}
public function getPaginated(
$count,
$pages,
$sortBy,
$sortOrder,
$projectAll
) {
$this->count = $count;
$this->pages = $pages;
$this->sortBy = $sortBy;
$this->sortOrder = $sortOrder;
$this->maxPerPage = 10;
$this->projectAll = count($projectAll);
$dreamsResponse = new ProjectResponse();
$dreamsResponse->setSelfPage($this->getSelfPage());
$dreamsResponse->setNextPage($this->getNextPage());
$dreamsResponse->setPrevPage($this->getPrevPage());
$dreamsResponse->setFirstPage($this->getFirstPage());
$dreamsResponse->setLastPage($this->getLastPage());
return $dreamsResponse;
}
private function calculateNbPages()
{
return (int) ceil($this->projectAll / (int) $this->count);
}
/**
* Returns whether there is next page or not.
*
* @return Boolean
*/
private function hasNextPage()
{
return (int) $this->pages < $this->getNbPages();
}
/**
* Returns the number of pages.
*
* @return integer
*/
private function getNbPages()
{
$nbPages = $this->calculateNbPages();
if ($nbPages == 0) {
return $this->minimumNbPages();
}
return $nbPages;
}
/**
* Return minimum number pages
*
* @return int
*/
private function minimumNbPages()
{
return 1;
}
private function getSelfPage()
{
return $this->hasNextPage() ?
$this->router->generate('get_projects', [
'count' => $this->count,
'page' => $this->pages,
'sort_by' => $this->sortBy,
'sort_order' => $this->sortOrder,
]
) :
'false';
}
private function getNextPage()
{
return $this->hasNextPage() ?
$this->router->generate('get_projects', [
'count' => $this->count,
'page' => $this->pages + 1,
]
) :
'false';
}
private function getPrevPage()
{
return $this->hasNextPage() ?
$this->router->generate('get_projects', [
'count' => $this->count,
'page' => $this->pages - 1,
]
) :
'false';
}
private function getFirstPage()
{
return $this->hasNextPage() ?
$this->router->generate('get_projects', [
'count' => $this->count,
'page' => $this->minimumNbPages(),
]
) :
'false';
}
private function getLastPage()
{
return $this->hasNextPage() ?
$this->router->generate('get_projects', [
'count' => $this->count,
'page' => $this->calculateNbPages(),
]
) :
'false';
}
}
Я решил эту проблему, мне нужно создать queryBuilder и использовать sort_order sort_by и count, а затем я отправляю queryBuilder в $ projectResponse-> setProjects ($ queryBuilder);
public function getProjectsAction(ParamFetcher $paramFetcher)
{
$manager = $this->getDoctrine()->getManager();
$repository = $manager->getRepository('ArtelProfileBundle:Project');
if (!$paramFetcher->get('status')) {
$queryBuilder = $repository->createQueryBuilder('project')
->where('project.currentStatus != :identifier1','project.currentStatus != :identifier2')
->setParameter('identifier1', 'fail')
->setParameter('identifier2', 'rejected')
->orderBy('project.'.$paramFetcher->get('sort_by'), $paramFetcher->get('sort_order'))
->setFirstResult($paramFetcher->get('count') * ($paramFetcher->get('page') - 1))
->setMaxResults($paramFetcher->get('count'))
->getQuery()
->getResult()
;
} else {
$queryBuilder = $repository->createQueryBuilder('project')
->where('project.currentStatus = :identifier')
->setParameter('identifier', $paramFetcher->get('status'))
->orderBy('project.'.$paramFetcher->get('sort_by'), $paramFetcher->get('sort_order'))
->setFirstResult($paramFetcher->get('count') * ($paramFetcher->get('page') - 1))
->setMaxResults($paramFetcher->get('count'))
->getQuery()
->getResult()
;
}
$projectAll = $repository->findAll();
$paginator = $this->get('paginator');
$pagination = $paginator->getPaginated(
$paramFetcher->get('count'),
$paramFetcher->get('page'),
$paramFetcher->get('sort_by'),
$paramFetcher->get('sort_order'),
$projectAll
);
$projectResponse = new ProjectResponse();
$projectResponse->setProjects($queryBuilder);
$projectResponse->setSelfPage($pagination->getSelfPage());
$projectResponse->setNextPage($pagination->getNextPage());
$projectResponse->setPrevPage($pagination->getPrevPage());
$projectResponse->setFirstPage($pagination->getFirstPage());
$projectResponse->setLastPage($pagination->getLastPage());
return $projectResponse;
}
Других решений пока нет …