How to use ->paginate() on your own data collection

I use ElasticSearch for storing a lot of product data but I still use Kirby as a CMS to manage the site, and to decide what products will get imported to ElasticSearch. Now to my question.

When I make a search in the ElasticSearch DB and return all the data I want to use some thing like:

$search = $esClient->search($params);
$results = $search['hits']['hits'];
$resultsObj = (object)$results;
$resultsObj->paginate(50);

The $resultsObj looks like this if I do a var_dump()

object(stdClass)#118 (100) {
  [0]=>
  array(5) {
    ["_index"]=>
    string(14) "XXX"
    ["_type"]=>
    string(7) "product"
    ["_id"]=>
    string(16) "123456"
    ["_score"]=>
    float(3.3088787)
    ["_source"]=>
    array(12) {
      ["name"]=>
      string(25) "XXX XXX"
      ["brand"]=>
      string(4) "XXX"
      ["price"]=>
      int(56900)
      ["finalprice"]=>
      int(56900)
      ["currency"]=>
      string(3) "SEK"
      ["imageUrl"]=>
      string(48) "https://www.company.se/bilder/1030517.jpg"
      ["description"]=>
      string(251) "XXX XXX XXX"
      ["category"]=>
      string(49) "Chairs; Möbler > Tillbehör möbler > Stolsdynor"
      ["merchantId"]=>
      int(27147)
      ["affiliateNetworkId"]=>
      int(112)
      ["affiliateUrl"]=>
      string(150) "http://pdt.tradedoubler.com/XXX"
      ["timeUpdated"]=>
      string(19) "2017-10-11 20:37:03"
    }
  }
  [1]=>
  array(5) {
    ["_index"]=>
    string(14) "XXX"
    ["_type"]=>
    string(7) "product"
    ["_id"]=>
    string(16) "123456"
    ["_score"]=>
    float(3.3088787)
    ["_source"]=>
    array(12) {
      ["name"]=>
      string(25) "XXX XXX"
      ["brand"]=>
      string(4) "XXX"
      ["price"]=>
      int(56900)
      ["finalprice"]=>
      int(56900)
      ["currency"]=>
      string(3) "SEK"
      ["imageUrl"]=>
      string(48) "https://www.company.se/bilder/1030517.jpg"
      ["description"]=>
      string(251) "XXX XXX XXX"
      ["category"]=>
      string(49) "Chairs; Möbler > Tillbehör möbler > Stolsdynor"
      ["merchantId"]=>
      int(27147)
      ["affiliateNetworkId"]=>
      int(112)
      ["affiliateUrl"]=>
      string(150) "http://pdt.tradedoubler.com/XXX"
      ["timeUpdated"]=>
      string(19) "2017-10-11 20:37:03"
    }
  }

Is it possible to “convert” the results so I can use the pagination function in Kirby?

You can convert an array into a collection:

$collection = new Collection($array);

The you should be able to use all collection methods including pagination.

So simple! Thank you for the excellent support.

Thanks to @pedroborges who brought this to my attention recently.

1 Like