Limit results in Apigility

I have created a code-related API with Apigility. At the moment I am using standard creation paths. My PostResource has a method called fetchAll($params = array()) . I created code for the method to return the required result set:

 /** @var HydratorInterface $hydrator */ $hydrator = new \Zend\Stdlib\Hydrator\ClassMethods(); /** @var PostService $postService */ $postService = new PostService(); $posts = $postService->findAll(/* Limit, default 10 */); $apiData = array(); foreach ($posts as $post) { $apiData[] = $hydrator->extract($post); } return new Paginator(new ArrayAdapter($apiData)); 

So far this is wonderful. If I go to the API URL, I get a paginated json representation of the data in my DB. If I set the page size for my API to 5. This will give me 2 pages and 5 results. So far, so good. The problem is that with every call (page 1 or page 2), all 10 results will be received from the database. It returns only 5 on one page, but 10 hydrates, etc.

Is there a way to use the limit, but also allows Apigility or paginator to know how many results are there in general, so that I get 5 lines and another pagination?

+5
source share
1 answer

I don’t know exactly how you retrieve the data, but, nevertheless, the following approach works as desired: the call chain looks like AddressResource#fetchAll(...) -> AddressService#getBar(...) -> AddressMapper#findAll(...) , and the data extraction method returns a Collection object.

AddressResource.php

 ... class AddressResource ... { ... public function fetchAll($params = array()) { $service = $this->getAddressService(); $collection = $service->getAddresses($params->toArray()); return $collection; } ... } 

AddressService.php

 ... class AddressService ... { ... public function getAddresses($params = array()) { $collection = $this->getMapper()->findAll($params); return $collection; } ... } 

AddressMapper.php

 ... class AddressMapper extends AbstractDbMapper { ... public function findAll($params = array()) { $select = $this->getSelect(); $select->where( ... ); $paginatorAdapter = $this->createPaginationAdapter($select); $collection = new AddressCollection($paginatorAdapter); return $collection; } ... } 

AddressCollection.php

 ... use Zend\Paginator\Paginator; class AddressCollection extends Paginator { } 

module.config.php

 return array( ... 'zf-rest' => array( ... 'AddressBookAPI\\V1\\Rest\\Address\\Controller' => array( ... 'page_size' => 5, ... ), ... ), ... ); 

Now the test: I call /addresses and watching the MySQL query log:

 $ tail -f /var/log/mysql_query.log ... 3 Connect root@localhost on address-book-api 3 Query SET NAMES 'UTF8' 3 Query SELECT COUNT(1) AS `C` FROM (SELECT `addresses`.* FROM `addresses`) AS `original_select` 3 Query SELECT `addresses`.* FROM `addresses` LIMIT 5 OFFSET 0 3 Quit ... 
+4
source

All Articles