phpnode.jswebsocket

Add node.js module into PHP Apache Application for real-time communication through websockets?


I have a dedicated, managed VM on top of which I host my web app, running on PHP (FCGI) and Apache. I built a REST API in PHP, everything of the web app is an endpoint, basically. That includes the chat messaging functionality included in the app, which is thus implemented using polling to simulate real-time messaging.

I would now like to really have an actual real-time messaging solution, but ideally with as much of the codebase written in PHP being used, and a minimum amount of added work as possible.

So I first looked at solutions for websockets in PHP, but I keep reading about articles saying that PHP is not the best for websockets.

So I thought about the following architecture:

I'm thinking of this solution because the messaging system setup is very tightly coupled to other components of the app, so rewriting the entire logic of it within node.js would take a significant amount of time and is at least currently not an option.

Is there any risk in this setup?


Solution

  • If PHP is not feasible for WebSockets for you, then you can implement a middleware in the technology of your choice, NodeJS seems to be it. The middleware would nor include any of the data processing, it would just handle the duplex WebSocket communication with the browser/app of the user and parse the events during the interaction with the browser/app into calls to your PHP app.

    So you will not have to migrate large codes from your app into NodeJS (you may decide to do so anytime, but you will not be forced to do so), but you will delegate the middleware abilities to NodeJS which will be a "postman" between the user browser/app and your PHP server-side. That way you will only need to implement a lightweight middleware that will keep the duplex channels up and running, receive some commands from the client-side, convert them into action calls that your PHP application can understand, send the requests (or execute command-line PHP, whatever method you prefer), get the answer that PHP provides and transmit it through the WebSocket duplex channel to the client-side.