mantas-done/short-closures

此包已被废弃,不再维护。作者建议使用mantas-done/short-closures包。
关于此包最新版本(v1.0.2)没有提供许可信息。

PHP的短闭包

v1.0.2 2017-12-17 12:58 UTC

This package is auto-updated.

Last update: 2024-03-12 08:56:24 UTC


README

目前PHP不支持短闭包的原生功能。但如果我们现在就能使用它呢?

// instead of this code:
$totalRevenue = $employees
    ->filter(function ($employee) {
        return $employee->district == 'Amsterdam';
    })->flatMap(function ($employee) {
        return $employee->customers;
    })->map(function ($customer) {
        return $customer->orders->sum('total');
    })->filter(function ($customerTotal) {
        return $customerTotal >= 75000;
    })->sum();

// you can do:
$totalRevenue = $employees
    ->filter('$employee->district == "Amsterdam"')
    ->flatMap('$employee->customers')
    ->map('$customer->orders->sum("total")')
    ->filter('$customerTotal >= 75000')
    ->sum();

它是如何工作的?这个库有一个函数可以将字符串转换为PHP匿名函数。

// instead of this code:
$anonymous_function = function ($x) {
   return $x * 2;
}

// you can do:
$anonymous_function = c('$x ~> $x * 2');

// or even shorter:
$anonymous_function = c('$x * 2');


// usage 
echo $anonymous_function(3); // output: 6

安装

composer require mantas-done/short-closures

语法

// all this syntax is valid
c('$x * 2');
c('$x ~> $x * 2');
c('($x) ~> $x * 2');
c('$x ~> {return $x * 2;}');
c('($x) ~> {return $x * 2;}');
c('($v, $k) ~> $v == 2 && $k == 1');
c('($v, $k) ~> {return $v == 2 && $k == 1;}');
c('($v, $k) ~> {$v2 = $v * 2; $k2 = $k * 2; return $v2 == 4 && $k2 == 2;}');

用法

此包可用于任何项目,但如果与其他包紧密集成,则优势最大。
例如,如果集成到Laravel Collection包中,可以移除c()函数的调用。
目前您可以使用c()助手将字符串转换为闭包

$totalRevenue = $employees
    ->filter(c('$employee->district == "Amsterdam"'))
    ->flatMap(c('$employee->customers'))
    ->map(c('$customer->orders->sum("total")'))
    ->filter(c('$customerTotal >= 75000'))
    ->sum();

或者,您可以将Laravel Collection类替换为提供的CollectionWithShortClosure类。然后您可以编写不使用c()助手的代码。
CollectionWithShortClosure仅适用于PHP 7.2或更高版本。

$totalRevenue = $employees
    ->filter('$employee->district == "Amsterdam"')
    ->flatMap('$employee->customers')
    ->map('$customer->orders->sum("total")')
    ->filter('$customerTotal >= 75000')
    ->sum();

短闭包可以集成到Laravel Eloquent中。但我没有提供此集成。

// instead of this code:
$users = User::whereHas('comments', function ($q) {
    $q->published();
})->get();

// it could be replaced with:
$users = User::whereHas('comments', 'published()')->get();

// ofcouse you can use it without tight integration, but it doesn't look nice
$users = User::whereHas('comments', c('$q->published()'))->get();

其他

有关PHP短闭包的更多信息https://wiki.php.net/rfc/short_closures