• Reading time ~ 1 min
  • 24.08.2022

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:

// Closure
Pipe::from('string')
    ->pipe(fn(string $value): string => 'prefixed-' . $value)
    ->get();
 
// Class-based methods
Pipe::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.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297