287 points · by acqbu · 4y ago · 332 comments
• 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.
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...
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).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".
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.
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.
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.
PHP has one of the best track records for retrocompatibility, this is really the worst thing you could pick to blame PHP for something.
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.
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
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.
[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.
And yes, it’s ok. Semver not a silver bullet.
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 you stick to modern versions and frameworks, it's a much different experience from PHP 8 years ago.
How is PHP/Laravel better? I'm of the opinion it loses hard in every aspect.
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).
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.
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.
I'm actually very interested in your dev setup. Do your devs use Linux machines? What IDE?
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.
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.
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.
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.
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 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.
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.
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.
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).
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.
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?
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.
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.
(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.
At which point there’s little difference from <everything else>.
And in my opinion PHP tends to be ugly and less readable by default.
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.
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.
Now with the cloud that advantage is utterly gone.
Python 1.0: January 1994
PHP 1.0: june 1995
Ruby 1.0: December 1996
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.
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.
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).
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.But it is infuriating having to namespace your code when a folder name/heirarchy could do.
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.
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.
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.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.