PHP Pipe Operator Package – Laravel News

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(‘https://blog.sebastiaanluc…….

npressfetimg-3045.png

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('https://blog.sebastiaanluca.com')

2 ->parse_url()

3 ->end()

4 ->explode('.', PIPED_VALUE)

5 ->reset()

6 ->get();

7 

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 = 'https://blog.sebastiaanluca.com/';

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

2Pipe::from('string')

3 ->pipe(fn(string $value): string => 'prefixed-' . $value)

4 ->get();

5 

6// Class-based methods

7Pipe::from('HELLO')

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.

Source: https://laravel-news.com/php-pipe-operator-package