Asynchronous Function Call in PHP
I am working on an a PHP web application and i need to perform some network operations in the request like fetching someone from remote server based on user's request.
Is it possible to simulate asynchronous behavior in PHP given that i have to pass some data to a function and also need output from it.
My code is like:
<?php
$data1 = processGETandPOST();
$data2 = processGETandPOST();
$data3 = processGETandPOST();
$response1 = makeNetworkCall($data1);
$response2 = makeNetworkCall($data2);
$response3 = makeNetworkCall($data3);
processNetworkResponse($response1);
processNetworkResponse($response2);
processNetworkResponse($response3);
/*HTML and OTHER UI STUFF HERE*/
exit;
?>
Each network operation takes around 5 seconds to complete adding a total of 15 seconds to the response time of my application given i make 3 requests.
The makeNetworkCall() function just do a HTTP POST request.
The remote server is an 3rd party API so i don't have any control over there.
PS: Please do not answer giving suggestions about AJAX or Other things. I am currently looking if i can do this through PHP may be with an C++ extension or something like that.
Solution 1:
Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).
The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.
The advantages are:
- Scalability - you can just add worker nodes to keep up with demand. In this way, tasks are run in parallel.
- Reliability - modern queue managers such as RabbitMQ, ZeroMQ, Redis, etc, are made to be extremely reliable.
Solution 2:
I dont have a direct answer, but you might want to look into these things:
- Recoil project - https://github.com/recoilphp/recoil
- php's LibEvent extension? http://www.php.net/manual/en/book.libevent.php
- process forking http://www.php.net/manual/en/function.pcntl-fork.php
- message brokers, i.e. you could start workers to make the HTTP calls and once that
job
is done, insert a new job describing the work that needs to be done in order to process the cached HTTP response body.