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:
- Install an additional node.js directory on my VM
- In that directory, setup a websocket server responsible for the handling of ws connections
- When a client successfully logs in, establish a new connection to the websocket server. The whole application traffic is though still going throught the REST API as until now. The ws connection is exclusively used to forward received messages to the corresponding client in real-time.
- Create an endpoint on the node.js server, e.g.
POST /forward-messages
, taking an array of e.g.{message: string, id: int}
objects as request arguments. When a request is received on that endpoint, themessage
is sent to the respective userid
s provided in the request that are currently connected with the ws server. - When a new message is sent through the REST API (e.g.
POST /messages
endpoint), everything stays as it is, plus: the endpointPOST /forward-messages
is triggered accordingly, internally.
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?