John Davidson

asynchronous - Making async calls for each record in php

0 comments
Message:


I have a file with 100 records. I want to read each record and pass it to another function.
However, since there are 100 records, I wish to trigger in async manner.


Current code :


foreach ($records as $record) {
$this->myFunction($record); //how to make this trigger all the function calls in one go ?
}

public function myFunction($record) {
//api call1;
//api call2;
//....
}


My Answer:
>function($record);
}_This code will process each record sequentially, one after the other. To make async calls for each record, you can use PHP's `curl_multi_init()` function to send multiple asynchronous requests at the same time. Here's an example of how you can modify your code to achieve this:

php
$mh = curl_multi_init();
$handles = [];

foreach ($records as $record) {
$ch = curl_init();
// Set up your curl options for each record
curl_setopt($ch, CURLOPT_URL, 'http://your-api-url.com');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Add the handle to the multi handle
curl_multi_add_handle($mh, $ch);
$handles[] = $ch;
}

$running = null;
do {
curl_multi_exec($mh, $running);
} while ($running > 0);

foreach ($handles as $ch) {
// Process the response for each record
$response = curl_multi_getcontent($ch);
// Call your function with the response
$this->function($response);
// Remove the handle from the multi handle
curl_multi_remove_handle($mh, $ch);
curl_close($ch);
}

curl_multi_close($mh);


In this code, we first initialize a multi handle using `curl_multi_init()`. We then loop through each record, create a new curl handle for each record, set up the curl options, add the handle to the multi handle, and store the handle in an array.

We then use a `do-while` loop to execute the multi handle until all requests are completed. Inside the loop, we process the response for each record, call your function with the response, remove the handle from the multi handle, close the handle, and finally close the multi handle.

This way, all requests will be sent asynchronously, and the responses will be processed as they are received.

Rate this post

5 of 5 based on 3095 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us