I admit it, I’ve started writing all of my new projects in Node.js. Why? Because most of them are lightweight and I want them to be real time.
PHP can be a real pain when it comes to doing anything remotely real time. First off, it’s designed to execute as quickly as possible and send a response to the client, which is of course good. However, what is bad about that is that it doesn’t stay alive - it does its stuff and then dies. Node.js on the other hand runs in a single process, which stays running all the time. This is perfect for real time applications because you can fire off an event to Node.js and then (say, using Socket.io) update the client, instantly. To do this in PHP would be nigh on impossible, due to its ’execute and die’ style.
Let’s just get it clear that this would not be a 100% real time application, but then how many truly are?
The first thing is obvious, when your application receives an event (be it a web hook hit, API request, user action, whatever) it can log it to a database, fine. You can then setup your client to poll an end point for those events and when it receives one, it can act on it. However, this is most definitely not a real time application and will have a huge overhead - depending on your polling interval - and most of those requests will be wasted considering there will be no events to notify the client of.
The second thing, which may not be quite so obvious, is when your next request comes in from somewhere that needs to be notified of this event, you can add some extra data to the response about what has happened. You can do it on page requests for browsers or on your (obviously not XML!) JSON response for your API end points. This way, you remove yet another layer of latency.
If you expect your client to be requesting pages or end points frequently (and I mean really frequently - every half second or so), you can probably do away with the polling method. If you expect the client to wait a while between requests then you can poll too.
If your client is a server (let’s say they’re requesting data from your API and want to be live updated when you receive an event), you can log their web hook end point in your database. When you receive that event, you can fire off a request to their end point and tell them what’s happened.
Of course, there are lots of other alternatives out there, such as using Python’s Flask or Django but this is about building real time application in PHP, not learning the ins and outs of Python web frameworks. By the way, if you do decide to move to Node.js from PHP, read this excellent article on asynchronous practices for PHP developers.