ReactPHP is Node.js in PHP


ReactPHP presents itself as bringing asynchronous programming into the PHP ecosystem.

In the past, whenever a Laravel project required some active functionality I resorted to Node.js.

Obviously, using a dual system with PHP and Node.js has disadvantages. In terms of architecture, you need to communicate between the Node.js and PHP, using Redis or MySQL, or direct HTTP calls. In terms of continuous development and delivery (CI/CD), they create a complication.

Recent versions of Laravel enable working directly with sockets, using either Laravel Echo Server or Laravel WebSockets. So this takes care of pushing from notifications from the server of the client.

Yet other critical aspects of the real-time operation and asynchronous operation are still left answered.

On a more general level, there are many situations in which you want to put up quickly a server, such as an HTTP server, socket server, or file streamer. These are easy to create in Node.js with its rich ecosystem of NPM modules. Programming these solutions with Laravel or any of the other common PHP frameworks is really complicated. Just think of the need to create the app, and then the controllers and actions before doing anything. And if you did it, you really have to program all by yourself.

It was in this context, that my colleague Grzegorz Bukat, have pointed me to ReactPHP. At first, I had resistance to looking into it. I live and breathe Node.js, so in any such situation, I can probably cobble together some Node.js server and somehow integrate it with the PHP. But eventually, I did study ReactPHP, and immediately liked it.

From the viewpoint of Node.js, the ReactPHP loop is immediately understood as the Node.js event loop. The difference being that the Node.js event loop runs under the hood, inside the Node.js V8 engine. In ReactPHP you actually have to create the loop and have it run:


Yet, with this single analogy, ReactPHP becomes immediately clear and usable to the experienced Node.js programmer.

In particular, the ReactPHP timers with addTimer and addPeriodicTimer give you the familiar JavaScript setTimeout and setInterval.

One may wonder if periodic jobs in Laravel do not do it. The answer is no. Because they are not intended for dynamic on the fly creation and destruction of timers.

Putting up a streaming video server in ReactPHP is a breeze as demonstrated in this excellent article ReactPHP Series. Having done this before in Node.js, it felt immediately clear and familiar.

Now armed with ReactPHP, I feel there is a new tool in my belt, and I can tackle new challenges with pure PHP.

One new concern that I have is how to integrate Laravel with ReactPHP. I hope to write about this in the future.

Yoram Kornatzky

Yoram Kornatzky