Using Kirby CMS Query Language Outside of Blueprints

Kirby comes with a powerful query language, that is mainly used in blueprints to build dynamic form fields, like select boxes with child pages or things like that. It can be extended by the filter syntax as described in the filtering compendium

Its simple dot notation gets translated to Kirby's PHP API, where

page.children.filterBy("featured", true)

is equivalent to

$page->children()->filterBy('featured', true)

As a developer, there are certainly moments where you wish you could write a query like that in a content field, instead of creating a complex query builder with form fields and then just parse that string and turning it to a native PHP Kirby query.

This is possible with the Kirby\Toolkit\Query class that "can be used to query arrays and objects, including their methods, with a very simple string-based syntax."

The following example queries Kirby's internal objects.

$siblings = new Kirby\Toolkit\Query('page.siblings(false)',[
    //'kirby' => $kirby,
    //'site' => $site,
    //'pages' => $pages,
    'page' => page()
]);

dump($siblings->result()->toArray());

But it's also possible to query a custom array or collection.

Convert an array into a Kirby\Toolkit\Collection to have all filter methods like findBy or count or filterBy available.

$collection = new Kirby\Toolkit\Collection([
    ['id' => 1, 'title' => 'Title 1'],
    ['id' => 2, 'title' => 'Title 2'],
    ['id' => 3, 'title' => 'Title 3']
]);

$output = new Kirby\Toolkit\Query('collection.shuffle.findBy("id",2)', ['collection' => $collection]);

dump($output->result());

Result:

Array
(
    [id] => 2
    [title] => Title 2
)

or

$output = new Kirby\Toolkit\Query('collection.shuffle.filterBy("id",">",1).data', ['collection' => $collection]);

dump($output->result());

Result:

Array
(
    [1] => Array
        (
            [id] => 2
            [title] => Title 2
        )

    [2] => Array
        (
            [id] => 3
            [title] => Title 3
        )

)

This is amazing and gives a lot of flexibility to developers who know what they are doing!

It's also worth to look into Kirby\Form\Options::query() that is mainly used for dropdown fields, but can provide some additional help, as discussed here.