问题描述
我想重构我的代码,并使用外部函数来实现匿名填充。
例如,我想重构以下代码:
更易读(没有匿名功能)。喜欢
$fulfilled = New Fulfilled($phones);
$rejected = New Rejected();
$pool = new Pool(...,[
'concurrency' => 15,'fulfilled' => $Fulfilled,'rejected' => $Rejected,]);
但是我如何找回我的&$ 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
函数中引用它。