adhocore / with
此包已被 放弃 且不再维护。未建议替代包。
With 提供了用于标量和非对象的类似于流畅的接口
v0.0.3
2017-10-26 15:50 UTC
Requires (Dev)
- phpunit/phpunit: ^5.7.0
This package is auto-updated.
Last update: 2022-10-01 08:06:05 UTC
README
- 对象化标量和非对象
- 流畅的方法链代替嵌套函数调用
- 适用于 PHP7
安装
composer require adhocore/with
使用
use function Ahc\with; // OR use Ahc\With\With; $val = ['a' => 10, 'b' => 12, 'c' => 13]; $with = with($val) // OR (new With($val)) ->array_values() // _ at the end means the current value is appended to the supplied arguments (default is prepend). ->array_map_(function ($v) { return $v + 2; }) ->array_sum() ; // Get the final result echo $with(); // 41 // Passing value through closures or class methods: with($value)->via(function ($val) { return $val; }); with($value)->via([new SomeClass, 'method']);
原因
TL;DR:与嵌套函数调用相比,提供更直观、更易理解和更少的认知负担。
你是否曾经需要在多层函数中传递一个标量/非对象?那么你可能最终不得不调用第一个函数,而逻辑上最后应该调用它。例如,如果你想在给数组的键加2之后求和它们呢?
// Without: array_sum(array_map(function ($a) { return $a + 2; }, array_keys($array))); // With: with($array)->array_keys()->array_map_(function ($a) { return $a + 2; })->array_sum();