GuyT
GuyT

Reputation: 4416

Async PHP requests

So, I want to create an asynchronous web service in PHP. Why? Because I've a nice async front-end, but Chrome will block my requests if I have more than 6 active TCP connections. Of course I have read some similar questions like:

but these don't cover my question.

I installed pthreads with the intention that I would be able to make multiple requests in different threads so that my PHP wasn't blocking other requests(in my situation I start eg. a long process and I want to be able to poll if the process is still busy or not).

PHPReact seems to be a nice library(non-blocking I/O, async) but this won't work either(still sync).

Am I missing something or is this nowadays still not possible in PHP?

class Example{
    private $url;   
    function __construct($url){
        $this->url = $url;
        echo 'pooooof request to ' . $this->url . ' sent <br />';
        $request = new Request($this->url);     
        $request->start();
    }
}

class Request extends Thread{
    private $url;   
    function __construct($url){
        $this->url = $url;
    }

    function run(){
        // execute curl, multi_curl, file_get_contents but every request is sync
    }
}

new Example('https://gtmetrix.com/why-is-my-page-slow.html');
new Example('http://php.net/manual/en/function.file-get-contents.php');
new Example('https://www.google.nl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=php%20file%20get%20contents'); 

The ideal situation would be to make use of callbacks.

ps. I have seen some servers(like Node.js) that are providing this functionality, but I prefer a native approach. When this is not possible I'm really thinking of switching to Python, Java, Scala or some other language that supports async.

Upvotes: 1

Views: 1147

Answers (1)

Joe Watkins
Joe Watkins

Reputation: 17158

I can't really make sense of what you are doing ...

  • Asynchronous and Parallel are not interchangeable words.
  • Threads at the frontend of a web application don't make sense.
  • You don't need threads to make many I/O bound tasks concurrent; That is what non-blocking I/O is for (asynchronous concurrency).
  • Parallel concurrency seems like overkill here.

Regardless, the reason your requests appear synchronous is the way this constructor is written:

function __construct($url){
    $this->url = $url;
    echo 'pooooof request to ' . $this->url . ' sent <br />';
    $request = new Request($this->url);     
    $request->start();
}

The Request thread will be joined before control is returned to the caller of __construct (new) because the variable goes out of scope, and so is destroyed (joining is part of destruction).

Upvotes: 3

Related Questions