boostphp/pipe-operator

此包已被废弃且不再维护。未建议替代包。

在PHP中实现管道操作符的唯一方法。

v1.2.1 2022-08-20 15:22 UTC

This package is auto-updated.

Last update: 2022-12-18 13:21:29 UTC


README

Latest Version on Packagist Total Downloads GitHub
Total Downloads

介绍

此包基于 Sara Golemon 和 Marcelo Camargo (2016) 提出的管道操作符 RFC,其中将问题解释为

PHP OOP 的一个常见模式是使用方法链,也称为“流畅表达式”。 [...] 这对于为流畅调用而设计的 OOP 类来说效果不错,然而,适应非流畅类到这种使用风格是不可能的,或者至少是不必要的困难的,对于功能接口来说则更加困难。

简例

比如说你想从URL中获取子域,你可能得到非常冗长且重复的代码,如下所示

$result = 'https://blog.github.com';
$result = parse_url($result);
$result = end($result);
$result = explode('.', $result);
$result = reset($result);

// blog

更多示例

查看 Golemon 和 Marcelo Camargo 的 RFC 以获取更多复杂和实际的示例。

安装

您可以通过 Composer 安装此包

composer require boostphp/pipe-operator

使用

您可以使用此包如下所示

use Boost\PipeOperator\PipeOperator;

$result = PipeOperator::from('https://blog.github.com')
    ->parse_url()
    ->end()
    ->explode('.', PIPED_VALUE)
    ->reset()
    ->get();

// blog

使用闭包

您还可以使用闭包以获得更大的灵活性

use Boost\PipeOperator\PipeOperator;

$result = PipeOperator::from('https://blog.github.com')
    ->pipe(fn ($value) => md5($value))
    ->pipe(fn ($value) => sprintf('prefixed-%s', $value))
    ->get();

// prefixed-740b375fe175853f9d4c5635194daf84

许可

MIT 许可证 (MIT)。请参阅 许可文件 获取更多信息。