PHP – The Right Way
phptherightway.com
phptherightway.com
• CGI-like execution model when used for the web, making resource leaks very difficult and encouraging scalable design
• not only integers and floats, but also strings, lists and dictionaries as mutable value types (copy-on-write) — this is a big difference from JavaScript and Python
• unusually for a dynamic “scripting” language: true classes and interfaces, and optional type declarations enforced by the runtime
• a standard library that doesn't require import statements!
• (a very new feature:) fibers, a way do asynchronous execution without every function in the callstack having to be aware of it
• binary-safe strings without presumptions from the language about what encoding is in use
• a very nice package manager
• a highly optimised runtime
But its history has made it a quite messy language which can be frustrating to learn, and which will always carry a higher mental burden than something like Python. It is a shame.
Lists and dictionaries are also mutable in Python. Strings are not. With CoW, are your referring to garbage collection? (value that is no longer assigned to a name will eventually be purged). That would be independent of (im)mutability, so I'm not sure I understand.
$a = ['a'];
$b = $a;
$a and $b both point to the exact same bit of memory. Thus passing an array between functions is zero-cost.When you do:
$b[] = 'b'; // append 'b'
a new array is allocated, the old data copied to it, and 'b' appended to it (basically, but IIRC, it is a bit more optimized than that).It's not static types FP like Haskell/Scala (or even TS), as it just recently started gaining some type safety, and while it had map/reduce call_user_func, it wasn't that big in PHP world.
It simply has/had too much mutability for it, and most PHP practice focused on trying to implement OOP ideas in it in a nice way.
You can do some pretty fancy things with arrays that you usually only see in FP type languages:
$arr1 + $arr2 (non-numeric keys) // scala: arr1 ++ arr2
array_merge($arr1, $arr2) // scala: (arr1 ++ arr2) distinct
array_unique(array_merge($arr1, $arr2)) // scala: arr1 union arr2
array_intersect($arr1, $arr2) // scala: arr1 intersect arr2
array_combine($arr1, $arr2) // scala: arr1 zip arr2
array_filter(array_map($mapper(...), $arr)) // scala: arr.flatmap(mapper)
in all of these cases, the original array(s) remains untouched. In most OOP languages, the array would probably be mutable (or require some juggling between mutable and immutable types, like C#). That's why its surprising. It's quite verbose in PHP, but the foundations for a FP approach is all there.What's even more surprising is when performance is comparable to a language like C# on some random benchmarks I've run[1] (opcache + JIT turned on in PHP, C# in "release" optimized compilation). I'd consider it a pretty good contender for serious things.
[1]: https://github.com/withinboredom/distributed-hashmap/blob/23...
• the value is locally mutable
• no duplication happens when you want to modify it and there is only a single reference
It's the main reason why I still prefer PHP for quick&dirty scripting and data processing.
`$a['1'] = 'string';` becomes `$a[1] = 'string';`. This appears to be the case for any fully-fledged decimal number where `(string)(int)$key === $key`
So if you are expecting `array_keys` to return all strings, you might get surprised
[1]: https://withinboredom.info/blog/2022/01/04/thoughts-on-php-f...
I consider this a non-feature in JS. The global namespace is enormous and growing rapidly. As I recall, PHP’s global namespace is similarly enormous (and notorious for its inconsistencies and redundancies). I understand that there are ergonomic advantages to not having to import built-ins, but I think framing it as a feature deserves a healthy asterisk :)
> fibers, a way do asynchronous execution without every function in the callstack having to be aware of it
This isn’t built into JS, but there’s an implementation of it, mostly used and popularized by Meteor. Again it has some ergonomic benefits, but I think it can too easily hide/obscure deoptimizations—eg performing IO operations in sequence which would be better performed concurrently.
The same thing can't really be said of the comments in here though. I don't see how emotionally charged debates over what is the "best" or "worst" language, help anyone.
It's almost as if some people can truly have their ego shattered, by someone on the internet liking another language than they do...
Couldn't we just agree that there is no "best" language for every possible use case, and that everyone is allowed to like whatever language they want to like? It's not like the whole bickering is going to change anyone's opinion.
Many teams and codebases these days have moved onwards and upwards toward a world where sensible design exists.
And the good news given to me by a colleague is that they pulled the same stunt going from 7.3 to 7.4. It's like depending on stumbling alcoholics instead of language designers.
Not much has changed since core devs tried to mitigate an overflow by testing for "$variable < MAXINT".
Yes you can build a great app in PHP. But so you can in Kotlin or Ruby or ...
Yes some have a career by starting with PHP. But that does not make it a good language for beginners. Same can be said (and to me is verrrry true) fro JavaScript.
Language design matters. It shapes how you think about code. Talk to people who've learned AND USED many languages including some esoteric ones like Haskell, a LISP or OCaml. Then see what they have to say PHP and JS for beginners.
* A welcoming, helping and open community.
* Built-in guidance or enforcement away from The Wrong Way and towards The Right Way. E.g. by making the former hard to do and the latter easy.
* Ecosystem of high-quality, properly designed libraries and sample code.
I see this in e.g. Rust. But e.g. JavaScript or PHP fail on all my three points. As does my main language, Ruby, sadly.
And I'm still not certain why not. You'll have a "hello world" in minutes. Even through something like Actix. Probably faster than your average "ruby on rails hello-world" or "react hello world". As those require a lot of up-front tooling to be set up.
I guess my reluctance is that Rust very early on requires knowledge of memory-management (borrower) and intricacies such as Result and Option.
While those are good to learn for a beginner at some point, that beginner probably wants to defer them to a moment that they have actual software deployed and dabble into multithreading, get runtime exceptions back and see the software crashing.
Still, I think languages that don't even allow you to think about such stuff, like Python, Ruby or JS, do the beginner a disservice: typing, shared-memory, runtime exceptions and undefined behaviour are a real thing, and a beginner should at least see that the libraries and examples all take these issues into consideration. Instead of waving it away with "we have tests to cover most of it. probably"
I'm Ruby dev, I deal with this daily; Learning Rust and using it in production has made me a much better Ruby dev.
I guess however we would need to define what a "beginner" target is, are we talking adults that want to learn programmed to change fields, or children wanting to inspire them to peruse programming as a career, or someone between the 2 groups
For children see this (very different objectives indeed):
For example, going straight-to-web can be hard since it involves several different concepts HTML is not CSS is not JS is not backend code (mostly!). So it is sometimes better to teach the basics in a desktop or console app using a single language with a single paradigm. Once they understand that, you could introduce other abstractions and explain why sometimes strong type-checking is useful and other times it is unecessary and time-wasting.
I learned programming to solve a problem I was having, in my case I did start out in web development in the 90's. I wanted a website that did something that I could not find premade software that did it in the way I wanted so I wrote my own. I also learned of open source and and other communities via this process.
Had I just stuck with the commercial software solution I bought, that was terrible, I would have missed out on on a skill I eventually learned to love.
The website (and company around it) I built was never successful, but from that experience I learned a skill that carried me to the career I now have
I was thinking about someone from school taking their first job. Or someone who has built a WordPress site and theme as a hobby and so on. I was not thinking about a 7-year old wanting to move a turtle around. Nor about an "arts student" looking if she may like webdev.
Though, a friend who has an after-school "tech" afternoon for young kids, includes a lot of arduino, adafruit and other hardware courses. Kids love it when some robot drives around the actual world, drawing lines. More than a virtual turtle drawing virtual lines. It requires C programming. He told me he has 8-year old kids writing some C.
In fact JS is much more pleasant to write than PHP, the main reason to move way from PHP after using it for over 10 years.
The majority of Gary Bernhardt's 2012 talk "wat"[0] is still relevant today with JavaScript. PHP's devs at least are actively trying to address the majority of issues people have had problems with, and have done so successfully for many of the issues it had.
In my opinion the only thing JavaScript has going for it over PHP is its ability to develop frontend and backend code using the same language, but then, you know, you'll need a million NPM dependencies if you pull in some of the simplest packages.
Until TypeScript takes over JavaScript I refuse to believe anyone who understands either languages fully prefers JS over PHP. I've yet to dabble in Deno, but I'm hoping that it also addresses much of the issues with JS, but I'm doubtful since it's also based on V8.
And yes, it’s ok. Semver not a silver bullet.
[1]:https://www.npopov.com/aboutMe.html
[2]:https://blog.jetbrains.com/phpstorm/2021/11/the-php-foundati...
I wish I was half as smart as he is.
In the Changelog section of the "count" docs at https://www.php.net/manual/en/function.count.php we find:
> 7.2.0 - count() will now yield a warning on invalid countable types passed to the value parameter.
So in 7.2.0 they started raising a warning in cases where the application was doing a stupid thing (calling count on a non-countable object). Notice that PHP's warnings won't stop execution by default. The expected side-effect here is that you get a warning in the logs and everything keeps working normally. Of course, many development setups halt execution on warnings, but this is a decision that devs make to "force" them to writte better code, not something enforced by PHP itself.
> 8.0.0 - count() will now throw TypeError on invalid countable types passed to the value parameter.
In the next major version, they turned the warning into an error. Pretty understandable way to improve the language I would say. Of course it would've been better if this was an error from the beginning, but given a mistake was made here, this is definitely the best way to correct it I can think of.
I'm sorry it took time for you to fix the legacy apps you've inherited. However, calling this out as an example of bad programming language evolution seems very wrong to me. I for one would LOVE that all languages and libraries in my project's dependency chains where as dilligent as in this example.
Breaking changes (at runtime no less) are the worst way to improve any language. They should have created a new count method if they wanted to change behavior in a breaking way. Forcing millions of developers to comb through their code just because some designer doesn't like the way someone else does something is just narcissistic.
p.s. Semver isn't worth the shit paper its printed on, it can't even version itself and all it does is give shit developers shit excuses to impose their own naval gazing induced shitstorms on other developers.
PHP has one of the best track records for retrocompatibility, this is really the worst thing you could pick to blame PHP for something.
But then when PHP does something positive to clean things up, we get threads like this. You're damned if you do and damned if you don't.
FWIW, how PHP handled `count` was very well done IMHO. The evolution from having `count` throw a warning on non-countable objects to having `count` throw a TypeError has occurred over several years! No one should have been caught off-guard by this very gradual change.
Instead of introducing a warning and informing the community that a feature was going to change or be removed in an upcoming major update, for years PHP just added new functions. You ended up with `mysql` and then `mysqli`. You ended up with the `mb_*` functions. And in order for developers to properly interface with all of these duplicate functions that may or may not be installed on your system, you ended up with jQuery-like libraries that would wrap certain portions of the PHP language and try to make them easier to work with. The comments on this (and most PHP posts on HN in general) are pretty crappy in large part because of decisions like this. It's also why the language basically died for like half a decade in the late 00s.
It's an absurd way for a language to evolve. At some point, you MUST fix the issues break backwards compatibility. You put out documentation and upgrade guides instructing developers on what needs to be done to facilitate the change. And as developers, we accept that we need to make sure we check that documentation before upgrading and in exchange, we get a better experience for developing new applications in the future.
Not everyone does. I think I've read a couple times how people commented that Python2->3 was the worst decision made by Guido. (I'm personally grateful that Py3 makes unicode default and more sane than Py2)
With every compatibility breaking release, you run the risk of splitting the language into two. Perl suffered that fate (though not only for that reason), and Python almost did (Py2 is still used in so many places 14 years after Py3 was released in 2008).
I think one of the differences here is how active the PHP community is. The Core devs are constantly taking ideas from the community and working those into or out of their plans for the future. They have open periods of discussion for any RFC and will engage with questions and concerns on Twitter and GitHub and Reddit and various other places. Those RFCs are voted on by 30+ different team members and requires a super majority to pass. Everything is transparent. Everything is discussed.
It's not perfect by any means (and the PHP-FIG standards group operated similarly and still splintered due in large part to egos), but it's not as one-sided as other languages and if you engage yourself in the community, you'll generally know what is coming and at least be able to voice your opinion in a forum that will be listened to.
Python 3.x has decided that breaking changes in minor releases is fine. My favourite: string prefixes (eg s'foo', u'foo') were legal in 2.x, removed in 3.0, added back in 3.3. There are other subtle breakages (eg open() flags).
Hating on PHP is a tired cliche at this point.
Python 3.0 was very much not a minor release, so your example is invalid.
The general point that Python does breaking changes in minor releases stands, but they do typically go through a deprecation period first.
Yes.
> PHP is actually a really decent option these days.
I beg to differ. What comparative options do you have experience with to base your claim on?
PHP has an amazing infrastructure of third-party libraries/packages around it, particularly if you're using PHP for web development. In comparison, Python simply does not have the same quality of framework for web like Symfony or Laravel. Django is good, but just that - good. And then there's the matter of speed with Python which is by all metrics slower than PHP.
Then there's node. Node is significantly faster than PHP, but all that speed is wasted away because of all that nightmarish mess that is node_modules. Node infrastructure for backend web dev is nowhere near close to where PHP or even Python is.
These languages all suffer from very similar problems.
Compare to C#/MVC.net, Kotlin/whatever, Go, Rust to get something noteworthy.
If it's just a matter of speed, PHP already is good enough for the great majority of cases. The bottleneck is the data layer, usually. If your problem is being faster than the latest versions of PHP can achieve, you can certainly look for Go/Kotlin/Rust. But if you start your startup optimizing trying to shave off some milliseconds out of a response time you are setting yourself for failure.
And in any case, languages like Go have their own part of quirkiness around the language or tooling (should we talk about how dependencies are managed in Go? that's ages behind npm/composer). Or shall we talk about the lack of exceptions, but then people regularly ask for them?
Agree about Rust, but I should differ from Go, as a disclaimer I never used Go, but read a lot of people switching from JS to Go and they have a very easy time doing so, maybe not everyone find it easy, and also it might to happen that the architecture you are used to work with in NodeJS is similar than the one that Go uses?
> If you are a startup with limited funds you are not able to target engineers workings with those languages.
I think Ruby/Rails will help you to build your project much quicker than Php/[Laravel | Symfony].
> If it's just a matter of speed, PHP already is good enough for the great majority of cases.
Again also Ruby is pretty fast these days (if you want more speed you can use JRuby or TruffleRuby).
> If your problem is being faster than the latest versions of PHP can achieve, you can certainly look for Go/Kotlin/Rust.
Go: I should say yes, if PHP/Ruby isn't enough, this should your go to. Kotlin: I cannot speak about it, I'm not sure how popular is in this space. Rust: I love rust but I think this should be your last resort, if Go isn't enough anymore.
But I can agree that work with Php is pretty easy (I worked with Php since 4.2 till 5.3, then tried it with some projects here and there with 7.x and 8.x) but I cannot stress how bad the tooling around php feels if you compare with others (ruby is bad too IMHO), JS with vscode, rust with rust-analyzer, etc. The only way I found a decent tool was with PhpStorm, but you need to pay for it (even the Laravel plugin needs a subscription), while the RubyMine is almost the same at least Rails works out of the box without an extra subscription for the plugins.
Yes for rust, not really for Go. I was able to pick up the basics of Go in less than a day, and the more advanced topics I was able to pick up not long after. OTOH I've tried to pick up Rust several times, and every time I just sit back in defeat.
> should we talk about how dependencies are managed in Go?
I'm curious what you're referring to here. Go's package management works, and is decent enough. No centralisation, and can work with just about any git repo.
- PHP gets you all the way from typeless prototype code to prove an idea, to expressive, runtime-enforced type checks that you can run in production.
- PHP doesn't require static compilation, but can be configured to compile to efficient Opcodes on the first run, making it competitive with Java/Kotlin/whatever speed-wise.
- PHP handles HTTP requests statelessly, starting with a blank slate in extremely short boostrap time. This pretty much eliminates memory leaks for common work loads. This execution model is very simple to reason about, and the major edge, I would argue.
- PHP has an exhaustive ecosystem with a great package manager. All code is namespaced, fetched directly from the source repository (eliminating several security concerns), and usually of high quality. Common frameworks are mature, solidly built, and feature-rich.
- PHP can also be used for other workloads outside of web applications: I've built a realtime message processing system handling thousands of messages per second, spread out across a dynamically scaling number of worker threads. It still happily processes messages as far as I know, and if you've ever received a business communication via messaging apps, chances are it was sent by my system.
All of these things make PHP an excellent choice for a wide range of projects, even compared to statically compiled languages, which you seem so keen to compare a dynamically interpreted language to.
How is PHP/Laravel better? I'm of the opinion it loses hard in every aspect.
Typically there are a lot more proficient PHP programmers than Ruby programmers around here, but if a company were open to remote workers the situation would right away change considerably.
There is also the price factor to take into account.
All in all, more often than not developer availability works itself into these choices.
It's a small investment.
Having your code in PHP is a liability considering great free alternatives exist. If you can do it in Kotlin and have your code in a well types language, that is a bit win down the line.
Having your code in PHP is no more a liability than having it in any other framework/language combo if you don't know what you are doing, and people that don't know what they are doing abound in any eco system.
PHP is just a tool, Ruby is just a tool. If you haven't spent an equal time in both you are probably not in a very good position to judge either. I've done a lot of PHP work, I've done a lot of Ruby programming and I dislike either with roughly equal passion to the point that if I never have to code up another website back end my life will be measurably better. The same goes for Python, Java, .Net, Go and whatever else we use to cobble together websites.
All of these are broken and leaky at multiple levels and the 'perfect' solution to build websites doesn't exist, in fact I don't think there is even a half decent one. This is a direct consequence of trying to shoehorn application development into a platform that was never meant to be used that way, but that's another discussion entirely. So you pick whatever is least offensive to you and your team, and probably you'll pick that which you are most familiar with or that seems to come closest to a fit for the kind of problem you are trying to solve.
But you know what? I would expect I would like Ruby/Rails as well, as it follows the similar kind of philosophy, which is server-side rendered templates with Javascript sprinkles.
I think Rails and Symfony both have the benefit of being a fairly consolidated solution. You don't seem to have the same proliferation of packages, as with Javascript.
What I'm not a fan of, is Javascript SPAs where there is no reason for using them.
Of course Taylor and the Laravel team have paid products, but they are all 100% focused on the Laravel ecosystem and developer experience!
Some of the things that the Laravel ecosystem has as first party packages / services:
Paid:
• Vapor - Serverless Platform. Run your vanilla Laravel apps on Lambda.
• Forge - Server Management. Builds Laravel ready servers on any cloud.
• Envoyer - Zero Downtime Deployment. Deploy your apps with push-to-deploy.
• Nova - Administration Panel. Completely code-driven admin panels.
• Spark - SaaS App Scaffolding. Basically a SaaS starter kit.
Free:
• Horizon - Queue Monitoring. Like Sidekiq
• Jetstream - App Scaffolding. SaaS starter kit with teams, invitations, api, etc.
• Echo - Realtime Events. Think Pusher, Socket.io, etc.
• Sail - Local Docker environment.
• Valet - Dev Environment for Macs.
• Mix - Webpack Asset Compilation. A sane wrapper around webpack.
• Cashier - Subscription Billing Integration. Stripe + Paddle.
• Dusk - Browser Testing and Automation. First party browser automation for tests.
• Sanctum - API / Mobile Authentication.
• Laravel Scout - Full-Text Search. Wrapper around Algolia, Melisearch, or full-text database searching
• Socialite - OAuth Authentication. Log in with GitHub, Google, etc. Dozens of community packages as well.
• Telescope - Debug Assistant.
That's all first party. It's unbelievable to me how many batteries are included. Then you start looking at the surrounding ecosystem beyond that and it gets even crazier.
Laravel as a community is an extremely welcoming place, and I have found that most people care deeply about their code and architecture, but don't pick each other to death on details that don't matter. I think all in all it's a pretty pragmatic group.
Performance. Ruby (with the official implementation) is brutally slow compared to PHP on Zend Engine [0], which is probably only behind the JVM in terms of VM performance and optimization for any language. PHP, if done properly, is a really great choice nowadays for a scripting language that can approximate C++/C#/Java levels of performance.
[0] https://benchmarksgame-team.pages.debian.net/benchmarksgame/...
Same for Ruby. I found them both slow compared to compiled to native langs.
JVM is also slow (especially startup)
If you stick to modern versions and frameworks, it's a much different experience from PHP 8 years ago.
1. Core API of stateless functions. Compare this to the bootstrapping requirements of, say, Java or Python;
2. CGI-like resource management in that you tear down everything after a request. Many people get upset at, say, the "global" keyword but "global" here just means "request-scoped". There are no STW GC pauses and it's difficult (but not impossible) to leak resources;
3. Executing code for a request is single-threaded. This is almost always what you want; and
4. PHP's copy-on-write arrays (that are really hash maps) that maintain insertion order are so incredibly useful and is almost always what you want.
Crapping on PHP for things like function inconsistency (eg functions that use underscores vs those that don't, needle/haystack inconsistency) is a tired cliche and boring at this point. It really adds no value complaining about things that just don't matter and/or are historical.
My biggest grievance is that Hack (FB's fork) is basically better in almost every way. The collection types (vec, keyset, dict) are better (eg less weird coercion defaults). The type system is leaps and bounds ahead of anything PHP has. Nullability as part of the type system is amazing. It's a shame Hack didn't become the dominant dialect.
As for the book, I went through it and it's really solid. Good job to the authors and maintainers. It covers a lot of issues like register globals, sanitizing input, Unicode and so on. It also has links to more detailed information on any of these topics.
3. Executing code for a request is single-threaded. This is almost always what you want;
And now with fibers you can launch "threads", which are not threads but work like them.But I did end up using CVS for seven years at a commercial company and I hated it with a passion. When I say I hate CVS with a passion, I have to also say that if there are any SVN users in Subversion, users in the audience, you might want to leave because my hatred of CVS has meant that I see Subversion as being the most pointless project ever started, because the slogan for Subversion for a while was, CVS done right or something like that.
And if you start with that kind of slogan, there’s nowhere you can go. It’s like — there is no way to do CVS right. So that’s the negative kind of credit.
https://singjupost.com/linus-torvalds-on-git-at-google-tech-...
I feel like you are stretching a quote to fit a premise that doesn't match the context of this thread or article.
Now, I don’t mean PHP is never the right way to go. Especially if you have to deal with a large existing code base, rewriting everything in whatever shiny bright language there is available currently on the shelve is probably a far worst option.
He hates C++ with a passion though. (Like CVS.) And .. it's understandable. C++ did not fix anything back then, that he cared about. Quite the opposite, only made things even worse for low-level code, because it was even more undecipherable by mere mortals. (And ... mostly still is.)
But, really, I suggest using other tools. We have nicer tools now.
Especially Laravel + Lighthouse, which is an extraordinarily neat GraphQL layer considering the huge deployability you get with PHP.
PHP is progressing towards a nicer language in a way that JavaScript, IMO, is not. And taking tens of millions of programmers with it.
I'm currently using Nuxt/Vue (static) on the front end, with Apollo (this latter bit I will probably swap out).
What is nice about Lighthouse is that it is schema-first. I am far less fond of the "auto schema" approach that e.g. WP-GraphQL uses. (Though WP-GraphQL is not bad; I'm also using that in a project).
I'd say Rails is a very nice DSL for building web applications that's written as an extension of Ruby.
We have two dimensions here, one for how easily a language allows you to build a website, and how expressive, consistent and error-proof a language is. It's easy to build a simple website with PHP (as it was with ASP and JSP, or even Cold Fusion). I actually like that approach, that maps running scripts to state transitions. But I also like the consistency and expressiveness of Python, Java, Scala, or C# (which I have used). As languages, they are "nicer" (and that's completely subjective) than PHP, and that niceness more than compensates for being unable to write code inside templates.
PHP has supported strict typing for a while now, making it also fairly consistend and error-proof.
There is nothing at all wrong with PHP and it's rapidly moving in the right direction.
The implication of the question is that there's something designed into PHP that makes it better for working with web things. Why does the language need to be designed to work with the web? That part of any language can be filled out with a framework quite easily, and arguably that means it's much easier to change how the language is used. That seems to be the case with every major PHP application anyway - most use Laravel or Cake or Symphony or something. Just as most Ruby web projects use Rails, and most backend JS projects use Express, and Rust web projects use Poem, and so on.
I don't think there's a good reason to design a language specifically for web projects. If that's how PHP works these days (I haven't used PHP in a decade or so), I'd suggest that might be a bad thing. It's very rigid, and if the language gets anything wrong that compromises the design of every project that uses it. Languages should provide simple primitives that frameworks and libraries build on.
That has always been the goal of PHP, to be a web framework in itself (and now we have frameworks on top of that framework). It's trivial to read POST data as understanding POST requests are built-in into the language. With Rust or JavaScript you either will pull down a external library to handle that for you, or write a ton of code to make it easier for yourself. With PHP, it's literally one-line of code.
It is not as rigid as you might believe, as we have frameworks on top of the native PHP framework already. That's not to say PHP is without compromises, it's not suitable for a bunch of different projects (you wouldn't write mobile/desktop apps with it for example). But if you have a simple CRUD application that just needs to output some HTML data and persist stuff to a MariaDB/MySQL database without wanting to pull down a bunch of 3rd-party dependencies, PHP will make that effortless compared to basically any other language.
I think the popularity of PHP for web development speaks for itself, it basically conquered that segment of development when it first appeared, and is still more-or-less king, even with its warts.
As a last word, I like that languages specializes in different things, not every language has to be a general-use language, and I hope we see more of that in the future. Darklang specializes in building backend APIs for example, others specializes in being for UIs and so on. As every language more or less looks like C today, there is plenty of room for innovation in programming language design (and no, not talking about TypeScript which is basically just C# that compiles to JavaScript, but more different languages).
This is untrue. PHP was a templating language and form-handler first and foremost[1]. It took a long time for it to move out of that (I'd argue up to 5.6) and become an actual programming language rather than a template language on steroids. Edit: we still have to move out of template mode in every file by adding a <?php at the top of our files - and don't ever add a whitespace char before that, or else.
So, essentially, we now have web-frameworks built in a templating language. With, ironically, template languages written in that templating language. Nice, if you like recursion though.
[1] Early PHP was not intended to be a new programming language, and grew organically, with Lerdorf noting in retrospect: "I don't know how to stop it, there was never any intent to write a programming language - https://en.wikipedia.org/wiki/PHP#Early_history
> PHP development began in 1994 when Rasmus Lerdorf wrote several Common Gateway Interface (CGI) programs in C,[16][17] which he used to maintain his personal homepage. He extended them to work with web forms and to communicate with databases, and called this implementation "Personal Home Page/Forms Interpreter" or PHP/FI.
He was working on his homepage (on the web) and wanted to make it easier to handle forms and communication with databases. That's basically everything the early web could do, and PHP aimed to make that easier.
My reply was more to explain why I think it is not a framework, but rather a language, to handle web-stuff. But looking at it from other perspectives, that can be "framework" just fine.
But no harm done, thanks for clarifying yourself :)
With Python and any of the Python frameworks, it's two lines. And one is most likely not explicitly bringing in HTTP request parsing, but just connecting all the plumbing.
> With PHP, it's literally one-line of code.
In that narrow domain, few things are simpler than Cold Fusion. If you go further, the Zope application server offers lots of nice ways to iterate over datasets that involve almost zero code.
> As every language more or less looks like C today
You seriously need to play more with other languages. I suggest you learn one or more of the "weird" ones, such as APL (avoid the ASCII notation, dig deep into the symbols), Erlang, or Lisp. It'll bring in a lot of perspective for you.
Yes, but in the case of PHP, PHP itself is the plumbing. You literally write `$_POST['param-name']` and you have the data. Using Python would require you to either write a bunch of logic enough to abstract it to have it like PHP, or require a 3rd-party library (or framework) for it to be one line.
> You seriously need to play more with other languages. I suggest you learn one or more of the "weird" ones, such as APL (avoid the ASCII notation, dig deep into the symbols), Erlang, or Lisp. It'll bring in a lot of perspective for you.
I'm saying this as someone who does play with lots of languages almost every day and my day-job is writing Clojure code (for both backend and frontend work). I might have missed a "As most of every new language" part in my previous statement. I'm not saying all languages are C-like, they're obviously not. But most of the popular new language do have a syntax-heritage stemming back to C (compared to languages with S-expressions), like Rust, TypeScript/JavaScript, Java, C++, C#, Python, Ruby, Golang and more, and they are mostly focusing on being general purpose useful.
Btw, I don't think lisp-like languages are the weird ones, the C-like languages are the ones that are weird. You should play around with more languages and you'll see why :)
IMHO this is still too much HTTP, as I'd prefer to keep the entire HTTP out of my app, but after your routers, there's nothing "Web": it could all be "domain specific".
Ruby, the language, is, indeed, hardly "Web" at all. Ruby stdlib has some HTTP stuff but that is both lacking and optional.
Consequence of that is that every other language is de facto is dominated by one framework provider that you almost always have to use. That in it self is the basis for a stagnant community.
Frameworks solves a general problem, you on the other hand solves a specific problem, sometimes those two are aligned, but many times they are not and then you are on your own.
> I don't think there's a good reason to design a language specifically for web projects
It definitely is because web has some unique properties and I think that one of the reason why we are unnecessarily shuffling JSON from backend to frontend where it is then transformed to HTML by async JavaScript (which gives a rather disjointed user experience), instead of sending a proper HTML document immediately from the server, because most backend languages suck when it comes to doing proper web.
Thus the industry creates these band aid solutions that constantly makes both the web and web development worse.
> language gets anything wrong that compromises the design of every project that uses it
Language design is overrated when it comes to producing customer value. What is important is how the general architecture works
* memory model (shared, per request, etc)
* request model (by the app or by the web server)
* resource model (mapping URL to file)
* compilation/build step
* deployment
* hosting
* tooling (IDEs, linters, testing, package manager, etc)
* how to scale
* available programmers
* community
PHP wins by these metrics.But if you want to have some fancy language feature to print out a proper HTML document, or what is more likely a JSON blob, go ahead, but it does not improve the end user experience at all.
This had tons of disadvantages.
Say CoolLang is such a language. Since is msall CoolLang has a micro standard library so has no DateTime or JSON, so you have a package manager and maybe 1 repo where 15 different JSON packages, you decide to use JSON_A but you also want to integrate with Amazon and they used JSON_B in their API and you also need to integrate with other API and this guys used JSON_A2 witch is an incompatible version of JSON_A. So now repeat for each web related function you have to decide for what package to use, if is compatible with whatever you use and review all it's dependencies, in the end you notice you depend on 100 packages and 3 years alter you have issues upgrading.
You maybe now will complain that JSON is included and the solution is to use the CoolFramework_V13 for CoolLang, with is incompatible with previous versions and is based on 100 packages that could explode when some dev decides he had a bad day and purch is package.
Isn't Poem just... several months old? Your examples of frameworks for other languages are mature and established. Is the Rust ecosystem moving that fast?
Debatable really. Within the web development space the options are rather limited in my opinion.
Options:
* Spring based apps - Downside JVM is a Resource hog
* Python, Ruby, etc - The web frameworks are in my opinion not as full featured. Same with CMS systems. Also requires more resources. Also have limited OO features.
* Go, Rust, etc - Really good choices for APIs but their web frameworks are also really lacking.
The tooling around PHP is really good and stable. The language itself, the downsides are very limited and the main one that remains valid is inconsistency of function parameters. The issues with bad code are generally the same ones that can be done in another langauge.
Usually one would have an IDE's auto completion to take care about function parameters, and in any case PHP8 has named parameters now to reduce whatever confusion (especially when optional parameters come into play) remains.
I'm actually very interested in your dev setup. Do your devs use Linux machines? What IDE?
We have two deployment modes:
- lambda
- ec2 instance
Depending on how you would like to target Lambda you have multiple options. On ec2 too.
We use VS Code on both Linux and MacOS. The tooling is kind of meh at the moment, Ionide is not ready for prime time we run into issues frequently with it. We are considering to switching to Rider soon.
https://www.jetbrains.com/help/rider/F_Sharp.html
* I do not have time to write your a detailed answer but I promise to get back with an article sometime this month.
I still use EC2 for everything, I haven't explored Lambda yet. I look forward to your article, thank you. Is dev.l1x.be where it will be posted?
They are sane languages with large ecosystems and solid frameworks for web-dev.
I've spent a lot of time using PHP professionally and then coding all my personal stuff in Python/Go/Scala/Kotlin/etc. I know the downsides of PHP and I know the upsides and I often prefer coding in other languages but PHP really does have it's place.
I'm sorry? Compete on what parameters?
Almost all frameworks win, hands down, in developer-friendlyness from WordPress. Many, if not most, modern CMSes can easily compete on security or performance. Many CMSes will win in user-friendlyness - for distinct use-case even more so. Many web-frameworks win easily in versatility: there's no way you can build a solid payment-service-provider in WordPress, build a Bookkeeping app, CRM, project-management, etc in WP. Yet these are fine in Java, .net, Rails, Django or even Rust.
The only place where I consider WordPress king, is for standalone, reasonably simple, blogs. This is a giant niche.
* standalone: not integrated into CRMs, or editorial workflow software. reasonably simple: no complex editorial and publishing workflows. blogs: anything slightly more than simple brochureware, but simpler than an avera CMSes.
I was saying this exact thing: WordPress is just a CMS, which severely limits what you can sanely do with it. You won't build a PSP in a CMS. That was my point.
> not many systems can compete with Magento/Spryker/Sylius
I'm evaluating eCommerce solutions for a Magento 1 upgrade path. I'm already evaluating Magento 2 and Sylius, but I've yet heard of Spryker. I found the PaaS offering, but even from their Github account I don't see any PHP application that would be an alternative to Magento or something based off Sylius. If you have any links or further information I've love to know. Thanks.I have to disagree. The JVM is one of the biggest pluses and might be one of the most battle-tested pieces of software out there.
> The web frameworks are in my opinion not as full featured.
Again, have to disagree here. Django is by far one of the most full-featured, well-documented web frameworks out there (IMO).
> The tooling around PHP is really good and stable. The language itself, the downsides are very limited and the main one that remains valid is inconsistency of function parameters. The issues with bad code are generally the same ones that can be done in another langauge.
I agree here and I think with PHP 8 incorporating JIT compilation, I think the future looks bright for PHP. I think the biggest foot guns these days are to be found in the JS ecosystem...but again, IMO.
Your points don't seem to conflict with the fact you need more resources to run a mimimal Spring Boot application than you would a Go application, a Python applicaton, a PHP application, etc. Because the JVM by default by the nature of how it operates needs more resources. I'm not saying anything other than that.
The fuck are you smoking? The JVM is one of the most mature, resource efficient, and fast language runtimes out there.
See, this is why nobody can take you people seriously.
As someone who has actually read the JVM specifications many times, has actively worked on a JVM implementation, and has a pretty good grasp on virtual machine design, I beg to differ.
But hey, I'll take the bait, what makes you think the JVM is a 'resource hog'?
That said, many Java applications themselves are resource hogs. Even my preferred IDE, the Jetbrains suite which I love, are resource hogs. Perhaps I'm simply not configuring it properly, but arguably I wouldn't ask an end user to tune JVM parameters any more than I would ask a car buyer today to set his timing or tune his mixture.
Ok, so you're saying that because a large, complex desktop application uses a lot of memory and is also written in Java that therefore the JVM is a memory hog?
Well then, given how much of a memory hog Chrome is, I guess we can all shitcan C/C++ as well.
Look, in any reasonable apples-to-apples comparison the JVM blows anything PHP has out of the water, including haxe, hiphop, etc.
And even if you write a PHP-to-bytecode compiler (e.g. https://github.com/jphp-group/jphp) then there are certain limitations to how fast and efficient any dynamically typed language can be. Look at all the shit V8 has to go through to do field lookups: https://v8.dev/blog/fast-properties
And then there's so much useless request-level overhead to PHP, even with pre-cached bytecode, you're never going to get even close in terms of latency to a well tuned JVM running something like spring boot.
And if you really hate Java as a language, you can always use something like Kotlin.
Actually, no. They said they didn't believe that.
> And then there's so much useless request-level overhead to PHP, even with pre-cached bytecode, you're never going to get even close in terms of latency to a well tuned JVM running something like spring boot.
I think the point you need to specifically define that the JVM needs to be well tuned kinda shows you know there is a grain of truth to the fact that you dislike so much.
And really comparing performance of a compiled language to an interpreted language is kinda cheating. Compiled should be faster.
From my experience I can run a Go application with the same performance requirements as a JVM application with less resources. For example, for the same requirements I had 50mb of ram assigned to a Go docker and 250 mb assigned to the JVM. I'm sure we all agree 250MB is not so much but that adds up. Then we get on to the fact it's quite common in the real-world to see lots of apps built on the JVM needing lots of resources, sure you can say that's the devs problem and if they just did it properly it wouldn't be the case but if so many people are doing it wrong then maybe it's being the JVM makes doing it wrong so easy. (Which was PHP's problem so many years ago)
You don't need to tune it to beat the pants out of a PHP-based solution.
Honest question, have you ever owned a large-scale, low-latency service in both Java and PHP, and have you compared latency characteristics between both runtimes?
No, if I've worked at a shop with a large scale low latency PHP app, they aren't not bothering their ass with Java, no need. They clearly have a highly comptent dev team who know their tools.
The only time I've dealt with Java is when companies are moving away from Java because their Java app is bloated beyond hell. They have a dev team that aren't highly comptent and think switching languages will help.
If I was dealing with the two, I would most certainly expect the Java one to handle scale better. But if I'm at lower level scale I would expect the PHP one to require less resources. Once PHP starts to scale up it can be a resource hog.
The reality is the comptency level of your dev team is the most important thing.
A think you need to remember, the JVM can scale massively well but the majority of systems don't need to scale well.
Citation needed.
For folks not wishing to switch frameworks and tooling every year, you can get a lot done with PHP.
I really like Django as an opinionated framework. I have also used Flask, Falcon, and FastAPI, all with good results in their own niche. I also like Play and Scala and Spring Boot with Java.
> For folks not wishing to switch frameworks and tooling every year, you can get a lot done with PHP.
You can also get a lot done with wood and nails, but that doesn't mean it's the best tool for all kind of jobs.
See Ken Thompson, Reflections on Trusting Trust, 1984 https://www.cs.cmu.edu/~rdriley/487/papers/Thompson_1984_Ref...
Please, don't ruin "JS bad" thread with facts. It's rude.
With PHP you can have your cake and eat it too. Have the productivity of a dynamic language, no compile step and a really smooth gradual typing experience with great tooling and linting.
I really can't think of anything other that familiarity why one would prefer JS/TS for server side stuff. Maybe async story but PHP 8 got fibers now so it might be catching up soon as well.
This is very strange to hear. Typescript error messages will show you a type mismatch and explain why one type isn't compatible with the other. What's an example of a cryptic typescript error message?
The problem is that the type system in TS can get crazy complex and has many uncommon features like structural typing. You need to have a really good mental model of how TS works to be able to make sense of what TS tries to tell you.
Won't this sentiment hold true for Rust as well? You need to have a good mental model of how Rust works, with all its borrowings and lifetimes, to understand what its errors are trying to tell you, and especially how to fix the problem?
The difference is that errors do a great job and telling you what went wrong and how you can fix it. You just fix one error after another and the borrow checker will guide you to the correct solution.
For example you get an error like:
error[E0433]: failed to resolve: use of undeclared type `Environment`
--> src/main.rs:9:19
|
| let mut env = Environment::new();
| ^^^^^^^^^^^ not found in this scope
|
help: consider importing this struct
|
| use foobar::test::Environment;
|
You could fix this error without knowing Rust.You obviously need to know the basics of systems programming to effectively program in Rust and some type errors get tricky, still it is a more interactive experience and you can just jump in while in TS just jumping in does not really work and the level of type safety relies on your skills as a developer.
Type 'Record<string, any>' is not assignable to type 'T'.
'Record<string, any>' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Record<string, any>'. (2322)
Would you have figured out that the solution to the problem was to omit the - factually correct - return type of the method?
Rust is not just better at error messages, it's playing an entirely different game.While I would not be able to figure out the solution to this problem from the error message alone, I would gather from it that typescript is telling me here that it cannot guarantee that it will satisfy the type contract, i.e. that the function will return a thing of the same generic type T as it received. This is useful information in debugging the type declaration of the function.
How npm works and the policies by company behind it.
PHP composer is much more sane than npm.
And all the different package controversies like leftpad.
Lots of bogus and malware packages.
Have you actually tried using for Nim for building a scalable web service or even just complex websites with auth of your choice? Nim does not even come close to what PHP has to offer in terms of solutions for every need you may have.
(The only proper) PDO tutorial: https://phpdelusions.net/pdo/
Organize a php project according to industry best practice: https://github.com/thephpleague/skeleton
PHP Best Practices - A short, practical guide for common and confusing PHP tasks: https://phpbestpractices.org/
Modern PHP Cheat Sheet - A to-the-point summary of all awesome PHP features: https://front-line-php.com/cheat-sheet
Laravel, PHP, JavaScript: https://freek.dev/
PHP security: https://paragonie.com/blog
One that baffles me is that 8.0 changed it so all scripts default to a "C" (i.e. english, ascii-only) locale. [0]
So this is now a scripting language that requires you to call `setlocale` for every script manually.
Contrast python, which tries to fix the locale so it's at least UTF-8 aware. [1]
[0]: From https://www.php.net/manual/en/migration80.incompatible.php "The default locale on startup is now always "C". No locales are inherited from the environment by default. Previously, LC_ALL was set to "C", while LC_CTYPE was inherited from the environment. However, some functions did not respect the inherited locale without an explicit setlocale() call. An explicit setlocale() call is now always required if a locale component should be changed from the default. "
It practice all these env config initialization things are handled by the php.ini, and/or by a framework.
(Plus using the mb_string ext is how any minimally sane string handling is done in PHP nowadays.)
Yes, probably in ~10 years the PHP world too will move to a unicode by default setup :)
But hey, progress!
The beauty of perl scripts, and later php templates, was in their BASIC-like simplicity. They were not secure or structured in any way, but very accessible.
Once you add these frameworks, you realize you could have started with Python or Java in the first place and get more mature infrastructure and better language along the way.
Now with the cloud that advantage is utterly gone.
The big win of those will be tighter frontend and development integrations that are just not as feasible with a different language stack (PHP/Laravel, Python/Django, Ruby/Rails).
Python 1.0: January 1994
PHP 1.0: june 1995
Ruby 1.0: December 1996
Granted, it still happened about a decade and a half ago, so I hoped the sarcasm using the word "new" would come through.
It did ;-) . But I frequently meet devs (young and old) that believe Python, Ruby and others are "new" languages. So I think it's worth mentioning they are not in any way.
Of course age does not equate maturity. Neither social acceptance.
I have the same access to my shared hosting, and the amount of money per year is peanuts.
https://murex.rocks is a static site that costs me pennies each month and has zero scaling issues. The site is fully automated too, built from CI/CD (Markdown converted to HTML) upon commits to a master git branch. But it was purposely designed to run on the cloud.
This isn't to say that shared hosting isn't a worthwhile option, just that cloud can be cheap albeit you do need to architect your project for using the cloud rather than lifting and shifting your existing LAMP stack and expecting that to behave the same.
With the advent of Chinese frameworks that solve C1000K problems like swoole, workerman and so on it even found its place as high performance interactive backend server.
If you look at the "multiple queries" results of the web framework benchmarks, you'll notice that the frameworks that use blocking database drivers have similar numbers e.g. raw Symfony is 13,543, whilst Spring is 15,979, despite the JRE being much, much faster.
https://www.techempower.com/benchmarks/#section=data-r20&hw=...
At which point there’s little difference from <everything else>.
The mod_php "share-something" question was always more relevant for ops people.
But architecture of PHP applications is simple and it works. I like simple.
And in my opinion PHP tends to be ugly and less readable by default.
There's nothing PHP specific about share-nothing architecture. It's often refereed to as stateless application layer in other camps.
And, with things like Flask or FastAPI, you get BASIC-like simplicity and immediacy with a language that has a concept-space that scales with your understanding of it.
What does this mean?
It had its benefits since those amateurs understood their use case and their users' capacity very well. But now all of that is gone and they are still stuck with a subpar language at the core.
The argument is that the language is "awful" and "subpar" because it has "early decisions" like "multiple thousands of built-in" global functions introduced by "language amateurs"?
Sorry, but I remain unconvinced.
I agree that there are real reasons that PHP fails as a language in particular use cases, but it seems rare that those reasons get articulated in these threads.
https://phptherightway.com/#php_and_utf8
This is a web language? PHP still has these kind of issues because of its culture: Get it done now and ignore any future costs.
There’s a ToC on https://leanpub.com/phptherightway but I can’t link directly to it as the in-page link uses JS. (I’m on mobile though, so I can’t read the source. Maybe there’s an anchor someone else could link to.)
To answer the bigger-picture question, the first thing I see (the above-the-fold part) upon loading the page (on both desktop and mobile) is a stylized ToC.
I tried PHP last year (or should I say Laravel) and didn't found any good, the type system is bad for a project like Laravel, you have too many different files where you declare things and the type system doesn't now, so you end up without autocompletions (and warnings or errors from the php interpreter) you only catch those at runtime (I'm too used now to get the errors before run a project, or at least get a hind from the editor/IDE).
Laravel has also a pretty active and productive community and so many things just work out of the box, I’m not sure if Go or Rust has anything comparable.
I have to mention: I didn’t touch Go for over a year now and never used Rust. I felt that Go is pretty easy to learn in its basics but quickly throwing things together for a prototype with DB access, I would go for PHP at any time.
I would not go with nodejs/deno because it doesn't feel a resilient foundation, let's say you put your php server out there, it wouldn't crash easily or if it "crash" would not kill the entire server, so there are benefits with php in that regard, it feels more easy to fire and forget.
Go should have my go to, but because never used didn't wanted to go that route, then Rust that is more painful than php in regard of the frameworks, there are not so mature ecosystem in the web category, but I can build a resilient system with rust, even I could write plain old sql that get's validated at compile time[1], that sounds amazing (well there are few drawbacks, but I like to be able to freely refactor the app in the future and the tooling tells me where I broke it, and with all other alternatives, except Go, there is no such library).
So this is more personal preference and php didn't meet my expectations, that doesn't mean that php is bad, but for me and my use case is, we cannot blame to php yet, but I think the core developers must push even harder the type system, offer better 1st party tooling and more guaranties in regard of the integrity of your program, this is one take of rust that if it compiles it works so when you do code review you only need to review the logic :)
In other languages, you can import code like this:
import mail as mailer
The external code ("mail") does not have to make assumptions how it will be called when it is used.In PHP, it is the other way round. Every piece of code needs to try avoiding namespace conflicts by prefixing the code with something like this:
namespace Illuminate\Mail;
Hoping the namespace (here "Illuminate") will not clash with other code.It would not prevent a clash with another "Illuminate" namespace.
The problem is that the developer of "Illuminate\Mail" had to introduce the "Illuminate" namespace and hope nobody else uses it.
Additionally it makes the code more complex. Every file needs to carry this "namespace ...." line now.
The consequence you mention is that one depends more and more on tooling and services.
In Python, "import" actually imports the code.
In PHP, the "use" statement you see everywhere does not. It only works because the code has already "magically" been imported.
Usually by composer. Thats why there are tens of thousands of hits for "clear composer cache" on Google. To just point out one issue with the dependecy on a fat stack to deal with a missing import system.
You can manual include, define your own extra auto loader and use interfaces to quick swap for custom implementations.
Like I said, +15 years. Composer is 9 years old. How do you think we handle this in our own Jurassic times?
You can manual include
I don't think that will work with any code that came out in recent years. Because it all expects that its dependencies are automagically included via composer.In practice, every PHP based web application starts with Laravel or Symfony these days. So you are thrown into the composer workflow right away. And it would be a nightmare to fight it.
And then if you start needing additional functionality you can start adding packages with composer one by one. Of course it'd be stupid to build your own version of Symfony with it, but the beauty is that you can stop at any point you want if it covers your needs. This sort of thing would be much more hassle with say Java, without using any frameworks.
I find PHP packaging and dependency management to be painless compared to both Python/Ruby.
This is similar to NPM’s organisation prefix (@foo/bar).
But yeah, I’m not defending the hacky way namespaces are resolved through autoloading. I do prefer actual language support for a module system (but Ruby suffers from this problem too).
With Rails 7 and Zeitwerk, the Ruby community has landed on a very similar auto-loading system as PHP now[2] with constants translating to paths by convention.
[0]: https://github.com/php-fig/fig-standards/blob/master/accepte...
[1]: https://www.php-fig.org/psr/psr-4/
[2]: https://github.com/fxn/zeitwerk#the-idea-file-paths-match-co...
I do wish they would extend auto loading for standalone functions and constants though.
I think that neither do make assumptions on how the code is called when used, only one is preventing name collisions.
You hope there are no other libraries
called mail in your import path.
Let's take Python for example. With Python, I am in control of the import path.I can put those two mail modules in:
stuff/mail
tools/mail
And then use them like this: from stuff import mail as mail1
from tools import mail as mail2
I don't have to hope for anything.Namespaces are defined by the 3rd party developer.
In Python, they don't have to do anything. The project that uses the code decides.
But it is infuriating having to namespace your code when a folder name/heirarchy could do.
Is this problematic for archive distribution?
In PHP the namespace is just a name added to every class construct and nothing else.
This is basically
class MyThing
the same as this namespace My;
class Thing
However namespaces was a pragmatic design choice that solved the community's problem with code organization and ever increasing project sizes and for that it worked pretty well because introducing namespaces didn't break any existing workflow.Today though I agree that proper module system would be nicer and now with PHP evolved even further it is perhaps time to introduce them.
Without having deep knowledge about PHP internals it feels like it would be possible to do because you can already today implement your own module system. Here is just something quick & dirty as a proof of concept.
module.php
<?php
return new class {
public const MY_CONST = 47;
private const MY_PRIVATE_CONST = 127;
// with PHP 8.1 you also have readonly properties
public string $myPublic = 'foo';
private int $myPrivate = 17;
public function helloWorld(string $name): void
{
echo "Hello, World {$name}!";
}
};
main.php <?php
final class ModuleException extends Exception {
}
function module(string $name): object
{
static $modules = [];
if (isset($modules[$name])) {
return $modules[$name];
}
try {
$module = @require $name;
} catch (Error $error) {
throw new ModuleException("No such module {$name}", 0, $error);
}
if (!is_object($module)) {
throw new ModuleException("Module {$name} is not an object");
}
$modules[$name] = $module;
return $module;
}
$my = module('module.php');
$my->helloWorld('Module system');
$other = module('module.php');
assert($my === $other);
The building block in PHP internals is the class - interfaces, traits and enums are all classes in disguise. Could it be possible to use classes for modules as well? Perhaps just add some syntactic sugar on top.Is the strict_types dance necessary for this?
I really hope that if PHP introduces an import system, it does not combine it with stricter type handling.
No, just that PhpStorm adds this for me and I always have it my files. I have removed it now to avoid any distraction to what I wanted to show.
Maybe not everything is "the right way" but at least the nullsafe operator is, I think.
I would _love_ to use asdf for everything, but outside a core set of languages/developers it doesn't seem to have the community around it.
There are tons of tools to get things done, PHP is one of the worst ones.
I worked on many greenfield projects in recent year where the conscious choice was made to use PHP.
For the majority of projects NOT using PHP is basically throwing money in the trash. Best deployment story. Great ecosystem.
> Decision are made based on "copying" other languages like Java, plus you always end up using lots of tools just to make your code safer.
This is a really big strength. PHP is able to learn from other languages and when implementing features can avoid mistakes that they made.
What kind of greenfield projects were they, and who was making those conscious choices? Without context it's just non-sense.
> For the majority of projects NOT using PHP is basically throwing money in the trash. Best deployment story. Great ecosystem.
What other technologies have you used in your experience, that came to conclusion?
> This is a really big strength. PHP is able to learn from other languages and when implementing features can avoid mistakes that they made.
Name features PHP avoided while copying.
B2B shop, Marketplace, lots typical CRUD stuff. I don't think there is much of a pattern.
Developers wanted to use PHP. Though of course here in Germany PHP is much more popular than in the states.
> What other technologies have you used in your experience, that came to conclusion?
For server-side stuff:
Ruby, Python, JS/TS, Squeak/smalltalk (yes actually in production)
Ruby used to have some productivity advantages because of Rails but these day, as PHP frameworks have caught up, I see many shops that did both PHP and Ruby going back to PHP.
> Name features PHP avoided while copying.
Those that PHP does not have? Not sure how to make a negative list.