Defer

Defer ( callable $callback )

Delays construction of the inner function until execution. Input is sent to inner function, and output is the output of the inner function. Defer is useful if for example constructing the inner function is resource-intensive.

Parameters

callback
mixed callback ( void )

A callback that returns either a FunctionInterface or an array. If the callback returns an array it will be passed as argument to Compose, which is then used as the inner function.

Examples

Example #1

Basic usage example.

<?php
use Webbhuset\Pipeline\Constructor as F;

$defer = F::Defer(function () {
    sleep(1); // Sleep to simulate fetching IDs from a database.
    $idMap = [
        'alpha' => 1,
        'beta'  => 2,
        'gamma' => 3,
    ];

    return F::Map(function ($value) use ($idMap) {
        return $idMap[$value] ?? null;
    });
});

$input = ['alpha', 'gamma', 'omega'];

echo json_encode(iterator_to_array($defer($input)));

// Output: [1,3,null]