PHP Pipe Operator Package
Published on by Paul Redmond
PHP Pipe Operator is a package by Sebastiaan Luca that provides a userland implementation of the pipe operator in PHP. A recent RFC proposed this feature for PHP 8.1 but is declined with a majority "no" vote.
This package aims to bridge the lack of native pipe operator by taking a value and performing one or more actions on it:
$subdomain = Pipe::from('https://blog.sebastiaanluca.com') ->parse_url() ->end() ->explode('.', PIPED_VALUE) ->reset() ->get(); // "blog"
Under the hood, the Pipe
class will call the native PHP methods such as parse_url()
, end()
, etc., however, using method chaining helps the readability of code and is potentially less error-prone than a one-liner or procedural code like the following:
$subdomain = 'https://blog.sebastiaanluca.com/';$subdomain = parse_url($subdomain, PHP_URL_HOST);$subdomain = explode('.', $subdomain);$subdomain = reset($subdomain);
When you need more flexibility, this package also supports custom closures and the use of class methods:
// ClosurePipe::from('string') ->pipe(fn(string $value): string => 'prefixed-' . $value) ->get(); // Class-based methodsPipe::from('HELLO') ->pipe([$this, 'lowercase']) ->get();
You can learn more about this package, get full installation instructions, and view the source code on GitHub. The author also wrote about this package on his blog: Enabling PHP method chaining with a makeshift pipe operator.