Skip to content

crocodile2u/chainy

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

18 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Chainy - a nicer way to apply a set of functions to a value

Have you ever written code like this?

$array = array_filter($array);
$array = array_map(
    $array,
    function($element) {
        // ... manipulations ...
        return $modifiedElement;
    }
);
sort($array);

Know what? You could do the same in a more readable and nice way:

$chain = (new \chainy\Chain)

    ->filter()

    ->map(
        function($element) {
            // ... manipulations ...
            return $modifiedElement;
        }
    )

    ->sort();

$array = $chain->apply($array);

Chainy is a pipeline of functions, where every next one gets input from the previous one's output. In the example above, when $chain->apply() is called on $array, it goes sequentially through filter(), map() and sort(). As you can expect, those methods are just wrappers for the PHP's built-in functions array_filter, array_map and sort.

This is how things go with chainy:

  1. Create new Chain instance.
  2. Setup the pipeline, adding elements to the chain (in this casem filter to get rid of empty element, map to apply some modifications to every element that survived filter, and then sort the resulting array).
  3. Call Chain->apply() on the input array. The result is the filtered, modified and sorted array.
$chain = (new \chainy\Chain)

+------> filter() --+
|                   |
|    +--------------+
|    |
|    +-> map(function()...) --+
|                             |
|    +------------------------+
|    |
|    +-> sort();
|
| $array = $chain->apply($array);
|                          |
|--------------------------+

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages