On Tue, 6 Oct 2020 at 14:09, G. P. B. <george.bany...@gmail.com> wrote:

> And once *again* short-closure don't *just* have the auto-import of the
> outer scope going for it.
> The other main features of the short closure are not applicable to a block
> syntax.
>  - the fact that there is an implicit return
>  - it is a single expression,
> **no* braces therefore it doesn't look like it creates a new scope.*
>

I'd like to come back to this. Actually there is a precedent in PHP where
braces don't create a new scope:

    $a = 1;

    {
        $a++;
    }

    echo $a; // 2

I'm not sure why this syntax was allowed in the first place, but it is. So
I wouldn't be bothered if we create yet another case of block not creating
a new scope.

I'd like to emphasize the use case brought by Andreas Leathley:
transactional scope. I'm doing more and more of this these days, and I find
it very appealing:

    $connection->transactional(function() {
        // send raw SQL queries
        // or create a scoped EntityManager
        // etc.
    });

This is, IMO, the only way to easily guarantee that any `return` will
commit the transaction, and any `throw` will roll it back. Otherwise, you
must remember to wrap your *whole* block with try {} and
catch/rollback/rethrow. That's a lot of clutter that you'll typically want
to avoid when you're repeating this in each and every method of every
service.

Now, the example above doesn't convey the purpose of the RFC on its own.
Let's put it into context, here is how one of my service methods looks like:

    return $connection->transactional(function() use ($authorId,
$activityId, $parentId, $comment) {

... and this is not the largest one. Let's see how it would look like with
this proposal:

    return $connection->transactional(fn() => {

This may not look like a big gain for you, but this would make all my
services look MUCH cleaner. And I'm not worried about scope leaking:
usually, the closure takes up most of my service method.

— Benjamin

Reply via email to