servo-php / fluidxml

FluidXML, the PHP library for manipulating XML with a concise and fluent API.
BSD 2-Clause "Simplified" License
458 stars 45 forks source link

[feature request] Add closures support #34

Closed wujekbogdan closed 7 years ago

wujekbogdan commented 7 years ago

It would be great if the following syntax was allowed:

$xml->add([
            'node'         => 'value',
            'another-node' => function (FluidXml $fluidXml) {
                $value = ... // Do something
                return [
                    'yet-another-node' => $value
                ];
            },
        ]);

In such case, the function (callable expression, technically speaking) would be called and the result of the function call would be assigned to the another-node node.

Thanks to this we would be able to write the code in the more consistent way. What do you think?

daniele-orlando commented 7 years ago

Thanks for the feedback.

Just to understand better your use case, what are the pros of passing a callable? A closure is useful when its purpose is to operate in a specific way in a given context. In your example its purpose is to return data but without a specific behavior related to the context. So my question is what are the pros compared to this?

$yetAnotherNode = function () {
    $value = ...; // Do something
    return [
        'yet-another-node' => $value
    ];
}

$xml->add([
    'node'         => 'value',
    'another-node' => $yetAnotherNode()
]);
wujekbogdan commented 7 years ago

So my question is what are the pros compared to this?

You're right, there are no real benefits except more concise code - everything is in one place. This is just a syntax issue. For people coming from JS background, such syntax is quite natural.

daniele-orlando commented 7 years ago

I maintain open the ticket, so if other people will find useful your proposal we can discuss it here and in case plan it for the next FluidXML release.

Thanks again for sharing your feedback.

ralphschindler commented 5 years ago

this would be highly useful +1 from me.