1

我正在开发一个命令行应用程序,并且我有这个处理业务逻辑的类。这个类有一些方法可以循环 a 中的所有数据\Generator并回显一些值。

我使用\Generator是因为这个命令行应用程序将循环十万个数据。我需要它在命令行中打印/回显运行中的输出

// 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(); 

这工作正常并且运行顺利,但这直接违反了 PSR1 2.3 副作用https://www.php-fig.org/psr/psr-1/#23-side-effects

如何在不违反 PSR1 副作用的情况下处理此解决方案?

4

1 回答 1

0

我在其他地方找到了答案(不和谐的 php 服务器)。这是我得到的方法。

// 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;
}); 

而不是echoSomeClass方法中使用它。我只是将回调函数作为第二个参数传递并在 index.php 上回显它

于 2020-05-11T18:21:02.320 回答