Ever wondered whether it is possible to write asynchronous code in PHP? Good news, it is! One of the most promising libraries is ReactPHP. It provides the powerful concept of event-driven, non-blocking I/O in PHP. Its core is an event loop, on top of which it provides utilities like stream abstraction and async network clients and servers. The library is written in pure PHP and its architecture is well-suited for high performance network servers and clients. The documentation and examples of ReactPHP’s components are quite detailed so it should be no problem to get started. The following example is a simple asynchronous web server written in ReactPHP which responds with „Hello World“ for every request.
$loop = React\EventLoop\Factory::create(); $server = new React\Http\Server(function (Psr\Http\Message\ServerRequestInterface $request) { return new React\Http\Response( 200, array('Content-Type' => 'text/plain'), "Hello World!\n" ); }); $socket = new React\Socket\Server(8080, $loop); $server->listen($socket); echo "Server running at http://127.0.0.1:8080\n"; $loop->run();
0 Kommentare