1 # pq\Connection: Asynchronous Usage
3 Whenever you start an asynchronous operation, you will have to probe pq\Connection::poll() to determine the current status of the operation.
5 You can then use the ***public readonly*** property pq\Connection::$socket with ```stream_select()``` to wait for read/write-readiness.
8 You cannot use the connection for anything else while an asynchronous operation is active.
10 ## Connect or reset asynchronously:
12 First, you can establish or reset a connection asynchronously.
14 ### Start asynchronous connect:
18 $c = new pq\Connection(null, pq\Connection::ASYNC);
22 ### Start asynchronous reset:
30 ### Complete asynchronous operation:
32 Keep in mind that you have to test for write-readiness once *before* starting the polling loop on connect/reset.
36 // wait until the stream becomes writable
37 $w = array($c->socket);
40 if (stream_select($r, $w, $e, null)) {
42 // loop until the connection is established
47 case pq\Connection::POLLING_READING:
48 // we should wait for the stream to be read-ready
49 $r = array($c->socket);
50 stream_select($r, $w, $e, NULL);
53 case pq\Connection::POLLING_WRITING:
54 // we should wait for the stream to be write-ready
55 $w = array($c->socket);
57 stream_select($r, $w, $e, null);
60 case pq\Connection::POLLING_FAILED:
61 printf("Connection failed: %s\n", $c->errorMessage);
64 case pq\Connection::POLLING_OK:
65 printf("Connection completed\n");
73 If you use an appropriate timeout in the ```stream_select()``` call and do something else at the end of the while loop, you probably got the idea...
75 ## Execute queries asynchronously:
79 $c = new pq\Connection;
80 $c->execAsync("SELECT 1+2+3; SELECT 2,3,4", function ($res) {
86 The body of the while loop looks slightly different, when executing queries asynchronously, because you only have to wait for read-readiness.
88 You can use the ***public readonly*** property pq\Connection::$busy to test if a call to pq\Connection::getResult() would block, and if so wait for read-readiness and then call pq\Connection::poll().
94 $r = array($c->socket);
96 if (stream_select($r, $w, $e, null)) {
100 } while ($c->getResult());
104 If pq\Connection::getResult() returns NULL, there's nothing more in the pipeline.