吞噬池:重构匿名函数后如何获得池响应

问题描述

我想重构我的代码,并使用外部函数来实现匿名填充。

例如,我想重构以下代码:

Pool with return anonymous

更易读(没有匿名功能)。喜欢

$fulfilled = New Fulfilled($phones);
$rejected = New Rejected();
$pool = new Pool(...,[
  'concurrency' => 15,'fulfilled' => $Fulfilled,'rejected'  => $Rejected,]);

我创建了一个满足这样的课程

fullfilled_class

但是我如何找回我的&$ result?

食堂是一个难题。

[编辑] 正如从Abiux所说的那样,一个类不是那么易读。我试图像这样在$ pool外部提取匿名函数

public function fulfilled($response,$index){
        $body=$response->getBody();
        $status=$response->getStatusCode();
        $reason=$response->getReasonPhrase();

        $result[] = [
          "userNumber"  => $this->phones[$index],"status" => $status,"reason" => $reason,"body"   => json_decode($body,true)];
   
        return $result;
  }
  // -------------------------------------
  public function get_async($phones){
   ...

    $client = new Client();

    $requests = function ($phones) use ($filter){
      foreach ($phones as $phone){
        $url="contexts?userNumber=$phone&$filter";
        yield new Request('GET',$url);
      }
    };

    $rejected = new Rejected();
    $pool = new Pool($client,$requests($phones),[
      'concurrency' => 2,'options'     => $options,'fulfilled'  => ['this','fulfilled',&$result],'rejected'    => $rejected,]);

    // Initiate the transfers and create a promise
    $promise = $pool->promise();
    // Force the pool of requests to complete.
    $promise->wait();
    return $result;
  }

但它也失败

解决方法

首先,不要将匿名函数替换为类。它不是更易读,也没有任何目的(据您的解释)。

第二,您可以将$result作为对象实例化的一部分传递给__construct(),然后在__invoke函数中引用它。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...