PHP PSR1 echo side effects

168 views Asked by At

I was working on a command line application and I have this class that handles the business logic. This class has some method that loops all data from a \Generator and echo out some values.

I use \Generator because this command line application will loop a hundred of thousand of datum. and I need it to be print/echo in the command line the output on the fly

// SomeClass.php
class SomeClass {
    //... some code here
    public function someMethod($someArgs) { 
        foreach ($this->isFromAGenerator() as $data) {
            // the data above from `isFromAGenerator` 
            // is a data that is being yield
            echo $this->isAnotherMethod($data);
        }
    }
}

// index.php
$someClass = new SomeClass();
$someClass->someMethod(); 

This works fine and running smoothly but this is directly violates PSR1 2.3 Side Effects https://www.php-fig.org/psr/psr-1/#23-side-effects

How can I approach this solution without violation PSR1 side effects?

1

There are 1 answers

0
KevDev On

I found an answer somewhere else (discord php server). And this is my approach I got.

// SomeClass.php

class SomeClass {
    //... some code here
    public function someMethod($someArgs, callable $callback) { 
        foreach ($this->isFromAGenerator() as $data) {
            // the data above from `isFromAGenerator` 
            // is a data that is being yield
            call_user_func($callback, $this->isAnotherMethod($data));
        }
    }
}


// index.php
$someClass = new SomeClass();
$someClass->someMethod($args, function ($data) {
    echo $data;
}); 

instead of echoing it inside SomeClass method. I just pass an callback function as a 2nd parameter and echo it out on index.php