Config filters
In Kirby we already have something called collection filters. In this post I will write about a solution I came up with that I now call config filters.
Introduction
Let’s say you have a plugin that output values from a collection. Maybe we want to the user to be able to change these values on different conditions.
Config.php
In $args
we have defaults
which is an array with default values from the plugin, that can be replaced. We can send other data as well, for example the current page object of the collection.
c::set('my_plugin.filter', function($args) {
$args['defaults']['title'] = 'hello world';
return $args['defaults'];
});
Plugin
I made some comments in the code.
// $item is a page object in a foreach loop
// Set up default values of the collection
$defaults = [
'title' => $item->title(),
'url' => $item->url(),
];
// Set results to defaults as fallback
$results = $defaults;
// Set the config to a filter variable
$filter = c::get('my_plugin.filter');
// Check if the config filter is an anonymous function
if(is_callable($filter)) {
// Call the config filter with defaults array and the page object
$callback = call($filter, [
'args' => [
'defaults' => $defaults,
'page' => $item
]
]);
}
// Set results to the config filter results if it's an array
if($callback && is_array($callback)) {
$results = $callback;
}
print_r($results); // In a real case you would probably return it from a function here
It may look much to do but it’s quite powerful for the user in the end.