Search code examples
phpyiichaining

"Piping" methods in methods chaining


Lately I implemented this behavior for yii: https://github.com/garex/yii-pipe-behavior

It's main purpose is to allow methods chaining for methods, that are getters. Something in such style could be implemented in any other language/framework. It's more like syntactic sugar for fanats of method chaining.

From readme:

For example owner has method gimmeAll, that returns array that we want to transform by another owner`s method, let it be toSomething. In old style we call:

$bla = Something::create()->toSomething(Something::create()->one()->two()->three()->gimmeAll());

But with this behavior we can do this in more elegant way:

$bla = Something::create()->one()->two()->three()->pipe('gimmeAll')->unpipe('toSomething', '{r}');

If unpiped method has single parameter, then we can omit '{r}' parameter and call it like:

$bla = Something::create()->one()->two()->three()->pipe('gimmeAll')->unpipe('toSomething');

So my questions are:

  1. Can it be really useful? I implemented this stuff in late night and still not sure.

  2. Could it be a "bicycle"? May be such stuff exists in another lang/framework?


Solution

  • Based on the results and answers from thread at yii forum

    No, it's not usefult and even superfluous. Some quotes from there:

    I think saving results in a variable and passing it to the other method is much cleaner, readable, better supported by IDE's and just more sane.

    class Something
    {
            public function gimmeAllToSomething()
            {
                    return $this->toSomething($this->gimmeAll());
            }
    }
    
    $bla = Something::create()->one()->two()->tree()->gimmeAllToSomething();
    

    It's a bit more code to type and test, but best programming practices aren't about typing less.


    Currently in real scenario I also used gimmeAllToSomething() approach. So we can think about it as a door where you do not need to go.