rfc:functional-elements

This is an old revision of the document!


This RFC is still in progress

Functional elements to work with aggregations

Abstract

A common pattern in PHP is iterating through a list of objects and executing certain methods of the objects. This is especially common when it comes to 1:n-relations (e.g. one object, n adapters). This proposal is meant to abstract those iterations in convenient functional constructs by adding method call iterators and iterator functions.

Current usage patterns

UC-1: Iterating over an aggregation of objects

foreach ($list as $element) {
    $element->method();
}

UC-2: Iterating over an aggregation of objects and keeping the results

$result = array();
foreach ($list as $element) {
    $result[] = $element->method();
}

UC-3: Iterating over an aggregation of objects and conditionally executing a method

foreach ($list as $element) {
    if ($element->conditionalMethod()) {
        $element->method();
    }
}

UC-4: Iterating over an aggregation of objects and conditionally executing a method while keeping the results

$result = array();
foreach ($list as $element) {
    if ($element->conditionalMethod()) {
        $result[] = $element->method();
    }
}

Extracted functions

spl_iterator_element_call()

array|bool spl_iterator_element_call(
    array|Iterator $iterator,
    string|array $methods,
    array $params = array(),
    bool $collect = true
)

Iterating over a list of objects, call method “testMethod” and get the list of results:

$result = spl_iterator_element_call($list, 'testMethod');

Iterating over a list of objects, call methods “testMethod” (with param “test”) and “otherTestMethod” (with param “other”) and get the list of results:

$result = spl_iterator_element_call($list, array('testMethod', 'otherTestMethod'), array('test', 'other'));

Iterating over a list of objects, call method 'testMethod' (with param “test1” and “test2”) and “otherTestMethod” (with param “other1” and “other2”) and get the list of results:

$result = spl_iterator_element_call($list, array('testMethod', 'otherTestMethod'), array(array('test1', 'test2'), array('other1', 'other2')));

spl_iterator_element_call_conditional()

array|mixed spl_iterator_element_call_conditional(
    array|Iterator $iterator,
    string|array $methods,
    string|array $conditions,
    array $params = array(),
    array $condition_params = array(),
    bool $collect = true,
    bool $finite = true
)
rfc/functional-elements.1205676655.txt.gz · Last modified: 2017/09/22 13:28 (external edit)