PHP code example of wwwision / relay-pagination

1. Go to this page and download the library: Download wwwision/relay-pagination library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

wwwision / relay-pagination example snippets


$loader = # ... instance of \Wwwision\RelayPagination\Loader\Loader
$resultsPerPage = 5; // edges to load per page

$paginator = new Paginator($loader);
$firstPage = $paginator->first($resultsPerPage);

foreach ($firstPage as $edge) {
    // $edge->cursor; contains the cursor string
    // $edge->node; contains the payload
}

// $firstPage->pageInfo; contains an object with pagination information

if ($firstPage->pageInfo->hasNextPage) {
  $secondPage = $paginator->first($resultsPerPage, $firstPage->pageInfo->endCursor);
  // ...
}

if ($secondPage->pageInfo->hasPreviousPage) {
  $firstPage = $paginator->last($resultsPerPage, $secondPage->pageInfo->startCursor);
  // ...
}

$loader = new ArrayLoader(range('a', 'e'));
$paginator = (new Paginator($loader))->reversed();

$page1 = $paginator->first(3);

Assert::same(['e', 'd', 'c'], array_map(fn($edge) => $edge->node, $page1->toArray()));
Assert::false($page1->pageInfo->hasPreviousPage);
Assert::true($page1->pageInfo->hasNextPage);

$page2 = $paginator->first(3, $page1->pageInfo->endCursor);
Assert::same(['b', 'a'], array_map(fn($edge) => $edge->node, $page2->toArray()));
Assert::true($page2->pageInfo->hasPreviousPage);
Assert::false($page2->pageInfo->hasNextPage);

$arrayLoader = new ArrayLoader($arbitraryArray);

$callbackLoader = new CallbackLoader(
    fn(int $limit, string $startCursor = null) => Edges::fromRawArray(...),
    fn(int $limit, string $endCursor = null) => Edges::fromRawArray(...)
);

$queryBuilder = (new QueryBuilder($dbalConnection))
  ->select('*')
  ->from('some_table');
$dbalLoader = new DbalLoader($queryBuilder, 'id');

$queryBuilder = $entityManager->createQueryBuilder()
    ->select('e')
    ->from(SomeEntity::class, 'e');
$ormLoader = new OrmLoader($queryBuilder, 'id');

$paginator = (new Paginator($someLoader))
  ->withNodeConverter(fn(string $node) => json_decode($node));

$paginator = (new Paginator($dbalLoader))
  ->withNodeConverter(fn(array $row) => MyModel::fromDatabaseRow($row));