Symfony restfull json分页

时间:2015-08-03 16:18:03

标签: php json symfony pagination restful-architecture

我需要使用分页创建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": [
  {

和所有数据,我在DB中有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';
}
}

1 个答案:

答案 0 :(得分:0)

我解决了这个问题我需要创建queryBuilder并使用sort_order sort_by和count然后我在$ projectResponse-&gt; setProjects($ queryBuilder)中发布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;
}