5 ms·
I am an experienced PHP developer - and I also ask the question "why asynchronous PHP" all the time - except in a different context. Every time I start thinkin
by laurencei 9y ago
I am an experienced PHP developer - and I also ask the question "why asynchronous PHP" all the time - except in a different context.
Every time I start thinking about doing some strange magic "asynchronous" function - I realise I can just use the standard queue systems built into most frameworks today. i.e. get the task - push it onto a queue - then do something else without waiting for the queue itself.
The thought of dealing with "forked" processes, memory leaks, strange race conditions etc and all the stuff that comes with async PHP does not seem worth it. It is very easy to "reason" logic behind a queue system. I can test it extremely well, and essentially break the process up into sub sections and not have to worry.
Note - I'm not saying there is no place for true asynchronous functions - but I think people reach for them in PHP when other easier solutions might suffice in the first place.
- EGreg 9y agoYes, but how do you handle the result? You will need a closure to store the context you had when you made the function call. That is async.
- laurencei 9y agoThe queue is given the command. The command has the functions I want to run, including the context and what I want done with the result. It can be a closure right up to a full class. Using a framework like Laravel I can even "chain" queued commands - so CommandA will queued, then call CommandB when it is done etc. I've never run into a situation that wasnt easily solved by this.
- EGreg 9y agoOK so what environment is the function being executed in? That environment is outside of PHP. Now when it comes time to do the callback, is the PHP thread still running, or not?
- meritt 9y agoOne example that I think fits very well is a websocket server. As you often have a large number of clients with long-running connections and relatively low-volume bidirectional communication, a single process running react/amp can easily handle hundreds or thousands of clients. The majority of the examples out there are indeed contrived and better suited to a queue system as you've described.
- jrs95 9y agoI’ve seen approaches that basically use a Node server + queues for this. I think this is how Laravel does websockets.
- francislavoie 9y ago+1 to this. I like Ratchet for websockets written in PHP. One nice thing is that I can share certain things like session code between my websocket server and my backend framework. Having both be in the same language, in the same project, makes things a lot cleaner for me.
- vatotemking 9y ago> queue systems built into most frameworks Note however that these queue systems are not really PHP. You need supervisor (Python) and beanstalk (C) for this to work. Laravel just abstracts it away. And its good if everything is working until its not (hard to debug).