Asynchronous PHP: Why?
sergeyzhuk.me
sergeyzhuk.me
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.
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.
The majority of the examples out there are indeed contrived and better suited to a queue system as you've described.
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).
The main challenge when going async isn’t learning new syntax. It’s dealing with non-linear flow control and with different abstractions.
So, I remain unconvinced that picking PHP’s comparatively obscure async ecosystem is a good longterm strategy.
https://amphp.org/ https://reactphp.org/
Was basically the article. r/savedyouaclick
I always wished js was sync by default and only async when you tell it to. Now you have the words async/await (and not too long ago promises, bluebird, waterfall), spread out all over your code for that since you only need async perhaps less than a quarter of your code base. but i dont see js ever becoming procedural first anytime soon.
then I discovered Elixir, i was curious to see how they tout their highly concurrent functional language solved this issue. and surprisingly its as simple as wrapping a block of code inside an async block. its such a pleasant experience finally having best of both worlds, especially coming from years of callback hells and trying to debug what becomes a set of spaghetti code for performing simple things.
I am confused by this. JavaScript is synchronous and blocking by default due to its single-threaded nature as far as I know?
Sure, async will yield different behaviors for functions than without that decoration but that's a very new language feature.
`let res = await someAsyncOperation();`
and whenever you want an async operation (non-blocking), thats when you do something like:
async { let res = someAsyncOperation() }
For example, in Javascript, you would often just have a top-level async function and stay inside async world the whole time.
Putting your example in the middle of some random code can already be done by calling a promise but not putting the downstream code inside its .then() block.
One of the nicest things about Javascript is the absolute simplicity of its concurrency model, one of those perks coming from its single-threaded nature. I look at something like C# and Kotlin with their BYO await semantics as something I'm glad Javascript doesn't have.
hack has language-level support for async tasks[^1]. and is 99% compatible with PHP.
On the other hand, I would love to see PHP8 bring language-level support for async tasks.
If you have only 1 external system that both indexes the data and stores it, this won't help you that much.
But if you have an indexing system and another, with many read slaves, that stores the data, then async will help you.
You will do 1 external io request to retrieve a list of ids/identifiers then as many replicas paralel requests to retrieve and format the data.
It works with MySQL, it doesn't with PostgreSQL. PostgreSQL has options for asynchronous queries, but it's clear than even the person who made them has never actually used them!
Take a look at the docs for pg_send_query: "multiple queries cannot be sent over a busy connection. If a query is sent while the connection is busy, it waits until the last query is finished and discards all its results."
If you actually try, it will block on the next query! Who wrote this useless library?
There is also no callback or anything, you simply have to allow it to block in order to pick up results. (There is the undocumented pg_select which might work.) Queries must be sent and received in order, and one at a time. You can't run 2 at once (say a long running query, then a quick short one later in your code). You can't even send another one while the first is running (and block), because that causes the results from the first to be discarded.
Very disappointed with PostgreSQL because of this.
In contrast MySQL has mysqli_poll() which actually works like you'd expect.
If I had a job that needed asynchronous database queries, I'd definitely pick MySQL.
I'll agree that the PHP Postgres API appears to be very low-level, and the fact that it does not offer callback support may be due to the fact that PHP doesn't have a standard event loop to plug into. There may be higher-level libraries that do better here. (I don't know much about PHP.) Postgres is perfectly usable in an async manner from other languages, however.
I just came here to say that ... neither was Javascript :)
I tried doing a relatively trivial async php script(basically a script that was supposed to make an outbound redis pubsub connection and outbound websocket connection and relay messages) using reactphp and found it to be nearly impossible due to language/framework constructs.
It was easy enough to make the outbound connections but there was no obvious way to actually pass messages between the two connections.
Async style really just does not seem to work well with php at all.
I ended up having to read the source code of ReactPHP and add the functionality to my framework. Sure it is not one line of code like with node, but it's not rocket science either. I would definitely recommend trying ReactPHP to see the benefits.
... our CPU has to wait and does nothing, instead of doing some useful job.
Please correct me where I'm wrong, but IIRC your CPU is never waiting if there is more work to be done. Yes, there is the overhead of context switching if you're using mod_php. Otherwise I think most operating systems are smart enough to make use of resources.EDIT: Maybe an OS expert can clear up how this works?
And if the language you're choosing is a slow interpreted language like PHP then I'm fairly sure the context switch overhead is negligible.
Most of the third-party packages were built during the promises and callback era, and I'm so happy I can still use them. Imagine if its a BC break ala python 3, that would certainly fragment the community and would hurt the adoption of version 7.x.x and above.
I'm not saying PHP is a better asynchronous language than NodeJS but I'd definitely be wary of JavaScript unless you're interested in compiling
If you're interested in compiling then there are some very good languages in that space that are not JavaScript, Go, #F, etc
True, but you can use TypeScript, which I expect is more advanced than PHP's typing.
>no native filter map reduce on hash table
What do you mean by that? There is Object.keys/Object.values/Object.entries.
>no explicit variable import into scope
What do you mean by this? You can import a variable from a module.
(is "/s" still a thing?)
That said though, the version of PHP you are talking about was written 23 years ago. The language has changed a tremendous amount over 23 years. The state of the tool 23 years ago would be a very poor reason to choose or avoid it today.
Hell, Java is roughly the same age as PHP. Nobody in their right mind would dream of using that first version of Java today. It isn't that the tool itself is bad. Rather, the tool has improved dramatically over the last two decades.
Also applies to JavaScript, and to be fair, many other scripting languages. None of them were perfect in v.1 and to add missing features it was often necessary to bend them in ways that are inconsistent with the rest of the language.
No language/tech stack is going to ensure success, or have no challenges. But learning from the past is not a weakness.
What's the lesson you are learning from?
The lesson I see is that any language, even PHP, will give you success if you "build something people want".
I read lots of startup "shutdown" stories - and I've not read one that mentioned the choice of "PHP" (or any language) as the reason for shutting down.
So if your comfortable with PHP - punch out what you need to get started...
Is it suitable for EVERY application? No. But then again, nothing is a one-size-fits-all solution for all problems.