phpfunctionobjectdynamically-generatedkirby

Building chained function calls dynamically in PHP


I use PHP (with KirbyCMS) and can create this code:

$results = $site->filterBy('a_key', 'a_value')->filterBy('a_key2', 'a_value2');

This is a chain with two filterBy. It works.

However I need to build a function call like this dynamically. Sometimes it can be two chained function calls, sometimes three or more.

How is that done?

Maybe you can play with this code?

chain is just a random number that can be used to create between 1-5 chains.

for( $i = 0; $i < 10; $i ++ ) {
    $chains = rand(1, 5);
}

Examples of desired result

Example one, just one function call

$results = $site->filterBy('a_key', 'a_value');

Example two, many nested function calls

$results = $site->filterBy('a_key', 'a_value')->filterBy('a_key2', 'a_value2')->filterBy('a_key3', 'a_value3')->filterBy('a_key4', 'a_value4')->filterBy('a_key5', 'a_value5')->filterBy('a_key6', 'a_value6');

Solution

  • $chains = rand(1, 5)
    $results = $site
    $suffix = ''
    for ( $i = 1; $i <= $chains; $i ++) {
        if ($i != 1) {
            $suffix = $i
        }
        $results = $results->filterBy('a_key' . $suffix, 'a_value' . $suffix)
    }
    

    If you are able to pass 'a_key1' and 'a_value1' to the first call to filterBy instead of 'a_key' and 'a_value', you could simplify the code by removing $suffix and the if block and just appending $i.