[PHP] A Meilisearch adapter for Pagerfanta
Published on 2023-05-21 • Modified on 2023-05-21
This snippet shows how to create a Meilisearch adapter for the Pagerfanta PHP library. As you can see, it is quite straightforward. I'll try to make a PR when I can find some time, don't hesitate to do it if you don't want to have this code in your application. You can use it like this:
$pagination = (new Pagerfanta(new MeilisearchAdapter($searchResult)))->setCurrentPage($page);
where $searchResult
is a Meilisearch\Search\SearchResult
object.
<?php
declare(strict_types=1);
namespace App\Search\Pager;
use Meilisearch\Search\SearchResult;
use Pagerfanta\Adapter\AdapterInterface;
/**
* Adapter which calculates pagination from a Meilisearch SearchResult object.
*
* @template T
*
* @implements AdapterInterface<T>
*/
final readonly class MeilisearchAdapter implements AdapterInterface
{
public function __construct(
public SearchResult $searchResult,
) {
}
/**
* @phpstan-return int<0, max>
*/
public function getNbResults(): int
{
return max(0, $this->searchResult->getTotalHits());
}
/**
* @phpstan-param int<0, max> $offset
* @phpstan-param int<0, max> $length
*
* @return array<int, T>
*/
public function getSlice(int $offset, int $length): iterable
{
return $this->searchResult->getHits(); /** @phpstan-ignore-line */
}
}
Call to action
Did you like this post? You can help me back in several ways: (use the "reply" link on the right to comment or to contact me )
- Report any error/typo.
- Report something that could be improved.
- Like and repost!
- Follow me on Bluesky 🦋
- Subscribe to the RSS feed.
- Click on the More on Stackoverflow buttons to make me win "Announcer" badges 🏅.
Thank you for reading! And see you soon on Strangebuzz! 😉
