Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async PHP | Processing data into several systems (Advice)

I'm building an integration that communicates data to several different systems via API (REST). I need to process data as quickly as possible. This is a basic layout:

  1. Parse and process data (probably into an array as below)

$data = array( Title => "Title", Subtitle => "Test", .....

  1. Submit data into service (1) $result1 = $class1->functionservice1($data);
  2. Submit data into service (2) $result2 = $class2->functionservice2($data);
  3. Submit data into service (3) $result3 = $class3->functionservice3($data);
  4. Report completion echo "done";

Run in a script as above I'll need to wait for each function to finish before it starts the next one (taking 3 times longer).

Is there an easy way to run each service function asynchronously but wait for all to complete before (5) reporting completion. I need to be able to extract data from each $result and return that as one post to a 4th service.

Sorry if this is an easy question - I'm a PHP novice

Many thanks, Ben

like image 475
Ben Rees Avatar asked Nov 27 '25 21:11

Ben Rees


2 Answers

Yes, there are multiple ways.

The most efficient is to use an event loop that leverages non-blocking I/O to achieve concurrency and cooperative multitasking.

One such event loop implementation is Amp. There's an HTTP client that works with Amp, it's called Artax. An example is included in its README. You should have a look at how promises and coroutines work. There's Amp\wait to mix synchronous code with async code.

<?php

Amp\run(function() {
    $client = new Amp\Artax\Client;

    // Dispatch two requests at the same time
    $promises = $client->requestMulti([
        'http://www.google.com',
        'http://www.bing.com',
    ]);

    try {
        // Yield control until all requests finish
        list($google, $bing) = (yield Amp\all($promises));
        var_dump($google->getStatus(), $bing->getStatus());
    } catch (Exception $e) {
        echo $e;
    }
});

Other ways include using threads and or processes to achieve concurrency. Using multiple processes is the easiest way if you want to use your current code. However, spawning processes isn't cheap and using threads in PHP isn't really a good thing to do.

like image 89
kelunik Avatar answered Nov 30 '25 11:11

kelunik


You can also put your code in another php file and call it using this :

 exec("nohup /usr/bin/php -f your script > /dev/null 2>&1 &");
like image 39
Avihay m Avatar answered Nov 30 '25 10:11

Avihay m



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!