Skip to content

Commit 99b2a3f

Browse files
Add section on pagination for custom Data Prviders
1 parent 4ae84f2 commit 99b2a3f

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

core/data-providers.md

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,3 +243,53 @@ final class BlogPostItemDataProvider implements ItemDataProviderInterface, Restr
243243

244244
If you don't want to use the built-in Doctrine system, alternative approaches which offer an integration with API Platform exist.
245245
* [Pomm Data Provider](https://github.com/pomm-project/pomm-api-platform): ([Pomm](http://www.pomm-project.org/) is a database access framework dedicated to PostgreSQL database.
246+
247+
248+
## Pagination
249+
250+
If you are implementing your own collection Data Provider, then you might also want to support pagination. You can do
251+
this by returning a `\ApiPlatform\Core\DataProvider\PaginatorInterface` instance. API Platform provides a few
252+
non-vendor specific paginators, e.g. `\ApiPlatform\Core\DataProvider\ArrayPaginator` and
253+
`\ApiPlatform\Core\DataProvider\TraversablePaginator`. See the [Pagination page](pagination.md) for more information on
254+
pagination.
255+
256+
You can access the paging information by injecting the `\ApiPlatform\Core\DataProvider\Pagination` service, and then
257+
using it within your Data Provider…
258+
259+
```php
260+
<?php
261+
262+
declare(strict_types=1);
263+
264+
namespace App\DataProvider;
265+
266+
use ApiPlatform\Core\DataProvider\CollectionDataProviderInterface;
267+
use ApiPlatform\Core\DataProvider\Pagination;
268+
use ApiPlatform\Core\DataProvider\PaginatorInterface;
269+
use ApiPlatform\Core\DataProvider\TraversablePaginator;
270+
use ArrayIterator;
271+
272+
class CustomCollectionDataProvider implements CollectionDataProviderInterface
273+
{
274+
private Pagination $pagination;
275+
276+
277+
public function __construct(Pagination $pagination)
278+
{
279+
$this->pagination = $pagination;
280+
}
281+
282+
283+
public function getCollection(string $resourceClass, string $operationName = null, array $context = []): PaginatorInterface
284+
{
285+
$page = $this->pagination->getPage($context);
286+
$itemsPerPage = $this->pagination->getLimit($resourceClass, $operationName, $context);
287+
288+
$data = [/* My results */];
289+
$results = new ArrayIterator($data);
290+
$totalItems = count($data);
291+
292+
return new TraversablePaginator($results, $page, $itemsPerPage, $totalItems);
293+
}
294+
}
295+
```

0 commit comments

Comments
 (0)