php-async
php-async copied to clipboard
Framework for asynchronous executing shell command in PHP.
PHP asynchronous execution framework
This framework allows you to execute asynchronously arbitrary shell command from PHP process. It features the following functionality:
- open file descriptors for communication between the PHP process and the child one. Right now we support reading child's STDOUT and STDERR.
- ability to query whether the child process has finished its execution
- query PID of the child process, possibly for sending signals to it
- read exit code of the child process once it has finished its execution
- pre-inclined for easy caching of the child process results
Examples of usage:
Most simple asynchronous execution:
'--name-of-the-argument', 'glue' => ' ', 'value' => 'value of the argument', ); $child = new ToolsAsyncResult($cmd, $args); // Your 'my-command --name-of-the-argument "value of the argument"' is being // executed right now. In the mean time you can do something useful in your main // PHP process. do_something_useful(); // When you decide you need the results of asynchronous child process, simply do // the following. If the command has not finished yet, your main PHP process // will sleep until the execution is finished. $result = $child->result(); if ($result['exit'] != 0) { // Whoups... The child process did not terminate with exit code 0. // Let's see, maybe there is more hints about what went wrong in the STDERR. $stderr = $result['stderr']; } // Now let's save the STDOUT from the child process somewhere. $stdout = $result['stdout']; ?>Run the asynchronous command and query whether it has finished:
'--name-of-the-argument', 'glue' => ' ', 'value' => 'value of the argument', ); $child = new ToolsAsyncResult($cmd, $args); // While the child process is running, and as we do not want to sleep in the // main PHP process waiting for the results, let's keep doing something useful. while ($child->isRunning()) { do_something_useful(); } // Now we fetched the child process results without actually sleeping a second // in the main PHP process. $result = $child->result(); ?>Additional file descriptors passed to your asynchronous command:
array('pipe', 'w'), ); $result = new ToolsAsyncResult($cmd, $args, NULL, array(), $extra_descriptors)->result(); // Let's see what our child command has communicated on the 4th file descriptor. $fd4 = $result['streams'][4]; ?>Example of synchronous caching:
result(); // But if we repeat the same thing over again, our results are already cached // and this time it happens instantaneously. All you have to do, is to implement // some cache storage bin. $result = do_something_asynchronously('my-command'); $result->result(); ?>Issues/Questions?
Do check the php-async.php file to see full options and features provided by the framework.