关闭产量

imc*_*iac 6 php php-7.2

我想提供一些数据。问题是该chunk方法需要关闭来完成这项工作。在这种情况下有没有办法像foreach循环一样产生数据?

public function yieldRowData(): \Iterator
{
    $this->transactionQuery
        ->getQuery()
        ->chunk(5, function ($collection) { // This is executed for each 5 elements from database
            foreach ($collection as $element) {
                yield $element->getId(); // I want this to be yield from this method (yieldRowData)
            }
        });
}
Run Code Online (Sandbox Code Playgroud)

我尝试了这个,但它只会返回最后的结果:

public function yieldRowData(): \Iterator
{
    $results = [];

    $this->transactionQuery
        ->getQuery()
        ->chunk(5, function(Collection $transactions) use (&$results) {
            $results = $transactions;
        });

    foreach($results as $transactionEntity) {
        yield $transactionEntity;
    }
}
Run Code Online (Sandbox Code Playgroud)

Chr*_*anM -2

尝试一下,它应该更类似于您的第一次尝试,同时实际上会产生一些合理的结果:

public function yieldRowData(): \Iterator
{
    $results = [];

    $this->transactionQuery
        ->getQuery()
        ->chunk(5, function(Collection $collection) use (&$results) {
            foreach ($collection as $element) {
                $results[] = $element->getId();
            }
        });

    foreach($results as $transactionEntity) {
        yield $transactionEntity;
    }
}
Run Code Online (Sandbox Code Playgroud)

添加以下评论的替代想法:将闭包传递给yieldRowData()以便使用块的内存效率:

public function workRowData(\closure $rowDataWorker)
{
    $this->transactionQuery
        ->getQuery()
        ->chunk(5, $rowDataWorker);
}
Run Code Online (Sandbox Code Playgroud)

$rowDataWorker可以绑定到应包含某些最终结果或可用于$this访问实例变量的变量。