yuloh / pipeline
A simple functional pipeline
Requires
- php: >=7.0
Requires (Dev)
- phpunit/phpunit: 4.*
- squizlabs/php_codesniffer: ~2.3
This package is auto-updated.
Last update: 2022-02-01 12:57:20 UTC
README
Introduction
yuloh/pipeline is a simple functional pipeline. You can easily chain functions together to process a payload. It's a lot easier to read, and there are less temporary variables than doing it the old fashioned way.
Goals
This package aims to expose the simplest API possible.
The programming language elixir has a pipe operator (|>
) which lets you easily chain functions:
1 |> inc |> double
I really liked that syntax, and I wanted to write a pipeline package where I didn't have to write pipe
or add
over and over, hence this package.
Why PHP 7 Only?
PHP 7 introduced the Uniform Variable Syntax, which means we can do this:
pipe('hello world')('strrev')('strtoupper')();
Instead of something like this:
pipe('hello world')->pipe('strrev')->pipe('strtoupper')->process();
Install
Via Composer
$ composer require yuloh/pipeline
Usage
To create a new pipeline, invoke the Yuloh\Pipeline\pipe
function with your payload.
use function Yuloh\Pipeline\Pipe; $pipe = pipe([1, 2]);
Once it's created you can keep chaining stages by invoking the pipeline. The stage must be a valid PHP callable.
$pipe('array_sum')('sqrt');
If you invoke the pipeline without a stage, the pipeline will be processed and the processed payload is returned.
$result = $pipe();
All together, it looks like this:
pipe([1, 2])('array_sum')('sqrt')();
Passing Arguments
When adding a stage, any additional arguments will be passed to the stage after the payload. For instance, if you were processing a JSON payload the pipeline might look like this:
use function Yuloh\Pipeline\Pipe; $pastTimes = pipe('{"name": "Matt", "pastTimes": ["playing Legend of Zelda", "programming"]}') ('json_decode', true) (function ($data) { return $data['pastTimes']; }) ('implode', ', ') (); echo $pastTimes; // playing Legend of Zelda, programming
In the previous example, json_decode
would be invoked as json_decode($payload, true)
to return an array.
Alternative Method Call Usage
You can also add stages as method calls instead of function arguments. It's a little more readable for pipelines that are only using standard functions.
pipe('hello world') ->strrev() ->strtoupper() ->get();
Testing
$ composer test
License
The MIT License (MIT). Please see License File for more information.