5 ms·
Asynchronous PHP: Why?
- foxhill 9y agoi'm sure the spec for async in php is well designed and implemented. (is "/s" still a thing?)
- tcd 9y agotl;dr for the most useless article I've ever read. See links: https://amphp.org/ https://amphp.org/ https://reactphp.org/ https://reactphp.org/ Was basically the article. r/savedyouaclick
- el_cid 9y agojust use NodeJS or Go
- slifin 9y agoJavaScript is a worse language than PHP in some ways, for example no native type hinting, no native filter map reduce on hash tables, no explicit variable import into scope 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
- nawitus 9y ago>no native type hinting 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.
- tiuPapa 9y agoUse typescript or flow if you want types.
- JupiterMoon 9y agoNow we are compiling (sorry transpiling). If we are going to do that why not use e.g. Go?
- jrs95 9y agoTechnically transpiling is just a more specific kind of compiling, so you’re not wrong in saying compiling.
- Franciscouzo 9y agoWhat's your point? All interpreted languages have to be compiled anyway, you have to create an AST, convert it to bytecode, and then interpret it or JIT it.
- Can_Not 9y agoIt takes 5 minutes to set that up. No reasonable person is going to switch languages for that reason.
- tiuPapa 9y agoBecause I want to use JS with types and compiler rather than runtime error? If you are using Go, why not use Rust?
- cdelsolar 9y agoYou joke but this is exactly what should be done. Python also has an async story that leaves a bit to be desired. Async/await etc is getting more and more use, but with async coroutine mocks and everything it seems easier to start over sometimes.
- jv22222 9y agoWhat are some of the best resources to use when getting started coding async PHP? Any tutorials?
- CharlesW 9y agoHere's a list you might find useful: https://github.com/elazar/asynchronous-php https://github.com/elazar/asynchronous-php
- EngineerBetter 9y agoPHP was originally called Personal Home Page Tools. Perhaps people should consider that before building large and complex systems using it.
- wvenable 9y agoSimilarly, I'd argue against using a tool designed for scripting Java applets in browsers for anything large and complex as well. /s
- hluska 9y agoYou know, I understand a certain amount of PHP bashing. It's far from the most sane language that I have ever used and parts of the syntax are flat out painful. 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.
- ams6110 9y ago> It's far from the most sane language that I have ever used and parts of the syntax are flat out painful. 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.
- laurencei 9y agoLike Facebook or Uber? Both started with PHP.
- guitarbill 9y agoSo you start with PHP, and you keep adding hacks on top of hacks, until you realise it's hopeless. But you're too invested, so you create a new language that is kind of compatible, and a JIT for good measure. Of course, I hope you got really successful, because you'll need serious engineering talent and money. No language/tech stack is going to ensure success, or have no challenges. But learning from the past is not a weakness.
- scribu 9y ago> When you already have a solid background in PHP, it will be much easier for you just to dig in some libraries and tools for your use-case, instead of learning a new language and a new ecosystem. 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.
- chriswarbo 9y agoThis sounds very plausible to me. As well as PHP, I've written a bunch of Java and threaded Java. I treat the latter two as different languages: yes you can use the same parser for both, but adding threads to the semantics also removes a lot of the mental models and assumptions we could previously make.
- deleted 9y ago[deleted]
- nkcmr 9y agojust use [hack](https://hhvm.com/ https://hhvm.com/). 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. [^1]: https://docs.hhvm.com/hack/async/introduction https://docs.hhvm.com/hack/async/introduction
- pbalau 9y agoI think you are missunderstanding this a bit, hack has async io. 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.
- phs2501 9y agoIMHO, the biggest reason to use a language like Node when you want to do async programming is that for any random library you choose there's a 98% chance that it properly supports async as well and won't block on you. For better or worse async is pervasive in the ecosystem. Even in good languages like Python that have (allegedly; I've not used them) good async frameworks, most libraries will block as it's the normal I/O mode for the language, which really limits what you can use. I can't imagine the situation will be any better in PHP.
- wyager 9y agoOr, even better, you could just use a language that works well with concurrent programming without having to shoehorn in abstractions that break 2% of the time. Go, Haskell, Erlang, take your pick; any of them will work correctly out of the box, even if some library does blocking FFI calls.
- whopa 9y agoPeople keep saying that Node is async native, but the GC is global and synchronous, and that property will bite you on availability even at moderate traffic, i.e. sooner than you'd expect.
- deleted 9y ago[deleted]
- Piskvorrr 9y ago"Asynchronous PHP; Why? Because it's there." I was expecting some actual reason.
- laurencei 9y agoI 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.
- jaequery 9y agoElixir has gotten this down perfectly. 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.
- wavefunction 9y ago>I always wished js was sync by default 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.
- romanovcode 9y ago> I always wished js was sync by default `let res = await someAsyncOperation();`
- jaequery 9y agoso, i was hoping for not even having to type in async/await and make this possible: let res = someAsyncOperation() and whenever you want an async operation (non-blocking), thats when you do something like: async { let res = someAsyncOperation() }
- always_good 9y agoI'm not sure what that's supposed to solve since you want to handle error/results at that top-level `async` in your example. 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.
- jameshilliard 9y agoI know a decent amount of php, but I'm primarily a Python developer who writes most code with asyncio and twisted. 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.
- francislavoie 9y agoI recommend looking at ZeroMQ for this
- jameshilliard 9y agoNot sure how that would help much, I needed something that could talk with redis and websockets and pass messages between the two. I was trying to use php since that's what the main portion of the application was implemented in so that I could share code, I ended up just using python in the end though.
- firefoxd 9y agoI remember when node was new and everyone was trying those real-time chat tutorials. After following the cliché tutorial i realized in order to share the session between node and the rest of the php app I had to basically hack it. 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.
- EGreg 9y agoOf course, when PHP was created its goal was not to be a programming language that can be used to build large complicated applications. When it happened there was no JavaScript and no asynchronous stuff in mind. I just came here to say that ... neither was Javascript :)
- obvio 9y agoEvent-driven asynchronous & concurrent & coroutine networking engine with high performance for PHP. http://www.swoole.com/ http://www.swoole.com/ https://github.com/swoole/swoole-src https://github.com/swoole/swoole-src
- ars 9y agoI tried to do this. Limited to the context of database queries. Run them asynchronously, and pick up the results later. 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.
- phs2501 9y agoMake multiple connections to the database. A transaction is at the "scope" of a connection anyway, and I don't think there are any useful semantics for multiple SQL statements being executed in parallel in a single transaction anyway, so it's likely Postgres is trying to save you from yourself here. 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.
- dillon 9y ago... 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?
- q3k 9y agoCorrect. If a process is waiting on a recv()/send() (or any other non-asynchronous IO syscall on Linux), the userspace process will go into (un)interruptible sleep and another process can be scheduled in it's place. When data is ready to process (or a signal needs to be delivered) the original process will be scheduled again and the syscall will return. It would be absurd for the CPU to busy wait on data. 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.
- osrec 9y agoOn the topic of asynchronous PHP, swoole (https://github.com/swoole/swoole-src https://github.com/swoole/swoole-src) is very interesting. Lacks documentation at the moment, but outperformed Node on a variety of tests I tried with MySQL.
- tylerjwilk00 9y agoBrace yourself for virtue signaling about how bad PHP is because <insert wart from 10 year old version>. On a less cynical note, working in both Node and PHP, async is often more cumbersome than it's worth (for me) and a queue suffices.
- vatotemking 9y agoSlightly off but, what I loved most about Node's async/await is that its backwards compatible with promises. 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.