News for hackers. Stuff that matters.
Re:PHP Pipes in 156 Bytes by RedShift1 on Thursday March 03, 2022 @10:50AM (#30542510)
Why wrapped in a class? Seems entirely redundant or am I missing something?
Re:PHP Pipes in 156 Bytes by tored on Thursday March 03, 2022 @10:58AM (#30542634)
PHP can't autoload functions, only classes. Thus if you wrap it in a static function inside a class you can autoload the the function by calling the class, Pipe::new(...), without doing a require "file.php".
Re:PHP Pipes in 156 Bytes by dten on Thursday March 03, 2022 @11:07AM (#30542781)
You can add a file import to composer, which is built into vendor/autoload.php automatically. I suppose this allows you to load this as a package...
Re:PHP Pipes in 156 Bytes by CiaranMcNulty on Thursday March 03, 2022 @11:13AM (#30542858)
That's not done lazily which is considered bad
Re:PHP Pipes in 156 Bytes by mkdirp on Thursday March 03, 2022 @10:59AM (#30542651)
That's what I was wondering too, especially considering there is a helper function that just wraps it. Seems rather unnecessary.

   <?php
   
   function pipe(...$args) {
     // Retrive first argument as initial value
     $value = array_shift($args);
   
     // Call the functions passing $value and assign its return
     foreach($args as $func) $value = $func($value);
   
     // Return computed value
     return $value;
   }
   
   echo pipe("10 WAYS to EAT more HEALTHY", 
     fn($s) => strtolower($s), 
     fn($s) => str_replace(" ", "-", $s)
   );
Works just as well.
Re:PHP Pipes in 156 Bytes by zowanet on Thursday March 03, 2022 @11:04AM (#30542735)
Passing the first argument as part of the variadic array isn't necessary.

Here's my version in only 66 bytes, what do I win? ;)

  <?php function pipe($v,...$p){foreach($p as$f)$v=$f($v);return$v;}
Re:PHP Pipes in 156 Bytes by kuroguro on Thursday March 03, 2022 @11:37AM (#30543205)
64! (if you don't mind calling a variable).

    <?php $pipe=fn($v,...$p)=>array_reduce($p,fn($a,$f)=>$f($a),$v);
Re:PHP Pipes in 156 Bytes by mkdirp on Thursday March 03, 2022 @07:03PM (#30548795)
I guess I was just removing the need for an unnecessary class, but that's fair.
Re:PHP Pipes in 156 Bytes by leftnode on Thursday March 03, 2022 @10:53AM (#30542560)
Perhaps you could extend the Pipe class and thus the pipe() method returns an object for chainability? That's the only reason I can immediately think of.
Re:PHP Pipes in 156 Bytes by adamrezich on Thursday March 03, 2022 @10:54AM (#30542577)
free functions scary