PHP Pipe Operator Package


August 6th, 2021


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:

1$subdomain = Pipe::from('')
2 ->parse_url()
3 ->end()
4 ->explode('.', PIPED_VALUE)
5 ->reset()
6 ->get();
8// "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:

1$subdomain = '';
2$subdomain = parse_url($subdomain, PHP_URL_HOST);
3$subdomain = explode('.', $subdomain);
4$subdomain = reset($subdomain);

When you need more flexibility, this package also supports custom closures and the use of class methods:

1// Closure
3 ->pipe(fn(string $value): string => 'prefixed-' . $value)
4 ->get();
6// Class-based methods
8 ->pipe([$this, 'lowercase'])
9 ->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.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.