在zf2中使用分页进行api

时间:2016-03-07 12:50:49

标签: php rest doctrine-orm pagination zend-framework2

我正在使用其余的api url http://localhost/cities运行列出城市的功能,以便将结果集设置为:

[
  {
    "status": "SUCCESS",
    "totalRecords": 1220,
    "cities": [
      {
        "id": 1,
        "name": "New York"
      },
      {
        "id": 2,
        "name": "Washington"
      }
      .....
    ]
   }
]

这是我的代码:

模块配置:

'listcities' => array(
                'type' => 'segment',
                'options' => array(
                    'route' => '/cities',
                    'defaults' => array(
                        'controller' => 'City\Controller\City',
                        'action' => 'listCities',
                    ),
                ),
            ),

城市管制员:

public function listCitiesAction() {
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET');
        header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");

        $response = array();

        $cities = $this->libraryService->listCities();
        if (isset($cities) && count($cities) > 0) {
            $response[] = $this->getCityResponse($cities);
        } else {
            $response['status'] = 'FAILURE';
            $response['errorCode'] = 578;
            $response['errorMessage'] = "No cities found";
        }
        return new JsonModel($response);
    }

private function getCityResponse($cities) {
        $citiesArray = array();
        $response = array();
        foreach ($cities as $city) {
            $citiesArray[] = ['id' => $city->getId(),
                'name' => $city->getName()
            ];
        }
        $response['status'] = 'SUCCESS';
        $response['totalRecords'] = count($citiesArray);
        $response['cities'] = $citiesArray;

        return $response;
    }

以上代码来自控制器,其中调用服务,并且从服务调用存储库模型以获取城市列表。因此,我使用Doctrine2 ORM列出了城市。我的问题如何在Doctrine2 ORM中插入分页脚本。

城市重置:

public function findAll() {
        return $this->entityManager->getRepository('Library\Entity\City')
                ->findBy(array('active' => true));
    }

0 个答案:

没有答案