HackerTrans
TopNewTrendsCommentsPastAskShowJobs

PHP – The Right Way(phptherightway.com)

287 points·by acqbu·vor 4 Jahren·332 comments
phptherightway.com
PHP – The Right Way

https://phptherightway.com/

347 comments

TazeTSchnitzel·vor 4 Jahren
PHP is a language with various features that might make it attractive to certain people:

• 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.
babuskov·vor 4 Jahren
* duct-tape style of arrays that Just Work(tm) as arrays, hash maps, etc. without having to use any boilerplate code.

It's the main reason why I still prefer PHP for quick&dirty scripting and data processing.
Navarr·vor 4 Jahren
I love PHP "arrays" but there is one tiny gotcha that becomes more important as we do type-safety stuff more and more.

`$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
dotancohen·vor 4 Jahren
Some years ago I was appending underscores to key strings to avoid that. We're talking PHP 5 era. But even at that time stdClass was available. Today, I much prefer either using a stdClass object or actually making a real class when I reach for an associative array. They still have their use cases, though.
withinboredom·vor 4 Jahren
I don't think fibers are that great. There's no indication that a function call will create a fiber and do things[1] that might screw with your current state. When you know fibers are around, you need to code more defensively.

[1]: https://withinboredom.info/blog/2022/01/04/thoughts-on-php-f...
diarrhea·vor 4 Jahren
> not only integers and floats, but also strings, lists and dictionaries as mutable value types (copy-on-write)

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.
withinboredom·vor 4 Jahren
With copy-on-write:

    $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).
kaba0·vor 4 Jahren
So basically what FP languages do?
eyelidlessness·vor 4 Jahren
Depends on the language. Many FP languages use persistent data structures, sharing some memory with derived/updated values.
TazeTSchnitzel·vor 4 Jahren
Well, what PHP does similarly avoids the risk of accidentally mutating shared values, but it's not the same:

• the value is locally mutable

• no duplication happens when you want to modify it and there is only a single reference
withinboredom·vor 4 Jahren
Surprising php has a lot of FP aspects.
pas·vor 4 Jahren
It .. really doesn't. (Sure, probably a tiny bit more than Python.)

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.
withinboredom·vor 4 Jahren
FWIW, I don't consider type safety a major issue with FP vs. OOP vs. procedural. I think type safety is just that, a safety net. I've ported things between C#, Scala, and PHP for fun, and regularly find PHP to be more concise due to it's lack of type safety than it being a hinderance. Sure, it sucks that the IDE can't help me out more (lack of generics cough) but static analysis tools really help there, like Psalm and PHPStan. As a side note, Psalm's security scans have pointed out security issues with the original code it was ported from, so that's something...

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...
[deleted]·vor 4 Jahren
fooyc·vor 4 Jahren
Pretty sure they meant immutable in that quote.
TazeTSchnitzel·vor 4 Jahren
No, I didn't! PHP's string and array types are neither immutable nor a reference type. In this way they are very different from what Python, JavaScript etc do.
synergy20·vor 4 Jahren
so is object(array,map,etc) in javascript, many scripting languages have non-primitives mutable, the OP seems wrong on this claim(e.g. only PHP does that)
TazeTSchnitzel·vor 4 Jahren
They aren't value types in JavaScript or Python, they're reference types (as are all types in those languages). Mutable value types are different from both mutable reference types (Python list, JS Array, strings in both languages, etc) and immutable reference types (Python and JS strings, Python tuples…)
eyelidlessness·vor 4 Jahren
> a standard library that doesn't require import statements

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.
asddubs·vor 4 Jahren
well, PHP does have proper namespace support so you can easily avoid collisions. although I don't really think it's that much of a problem either way
kyriakos·vor 4 Jahren
I think JavaScript global namespace is massive in the browser. Under nodejs things are much saner.
eyelidlessness·vor 4 Jahren
It’s increasingly almost the same, aside from very DOM/*ML rendering contexts, and getting more similar as time goes on. Which is good for portability but JS (ECMAScript/TC-39) is huge in itself, and the various compatible things in the JS runtime ecosystem (browsers/Node/Deno) is also huge. Node was historically more limited here but given how much the language itself is expanding they have to choose compat.
hooby·vor 4 Jahren
It's a decent website - a useful collection of information and links to additional information, that can serve as a starting point to learn more. For those who use PHP, or for those who'd like to learn to use it, this might be useful resource.

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.
pak9rabid·vor 4 Jahren
In its early days (version 4 and below) PHP was a bit of a mess. However it got its act together with version 5, as it implemented an object model almost on par with Java's, which I thought kind of set the standard for how OOP should be done. It's just unfortunate that much of the mistakes with version 4 and below had to be kept in order to preserve backwards compatibility.
lotyrin·vor 4 Jahren
More than the design of the language itself, the culture suffered (and still suffers to a lesser degree) from the legacy of those bad designs, such that if you wanted to avoid a whole ton of awful codebases, poor practices and mediocre developers you could have easily done so by putting a language barrier between you and them and "graduating" to some other language.

Many teams and codebases these days have moved onwards and upwards toward a world where sensible design exists.
dec0dedab0de·vor 4 Jahren
You're right, but you're missing the emotional damage many hackers of a certain age feel when they remember troubleshooting PHP problems, or constantly having to look things up, before they left for whatever their language of choice is now. People complaining about PHP are mostly just venting frustrations from 15 years ago.
eyelidlessness·vor 4 Jahren
I tend to stay out of these discussions, precisely because I have such negative associations from PHP 3-5, but I don’t want to shit on anyone (or make anyone feel shit upon) who uses PHP today. The language and ecosystem has clearly improved and matured a lot, and while I don’t have any interest in revisiting it, I respect that.
[deleted]·vor 4 Jahren
benjamir·vor 4 Jahren
A language that changes the semantics of functions between minor versions has no "right way". "count()"less examples of crap. I have currently two weeks of code migration behind me because code running correctly on 7.0 fails on 7.3 -- while I see the reason for change was necessary I also see the hopelessness of rebuilding a flawed house with a fundament build on a pile of manure.

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".
kilburn·vor 4 Jahren
I was curious about this rant since I'm maintaning a number of PHP projects and I haven't had any issues with "count".

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.
pluc·vor 4 Jahren
(2)
throwaway_r211·vor 4 Jahren
> In the next major version, they turned the warning into an error. Pretty understandable way to improve the language I would say.

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.
apocalyptic0n3·vor 4 Jahren
Perhaps ironically, this attitude towards backwards compatibility is a big part of what held PHP back for so many years and part of the reason why PHP 6 was abandoned during development and PHP 7 used none/almost none of that work.

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.
hnfong·vor 4 Jahren
> And as developers, we accept that we need to make sure we check that documentation before upgrading

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).
apocalyptic0n3·vor 4 Jahren
This is true. You see this happen all the time with frameworks where the community splinters because of a major change. It doesn't happen as often with languages (perhaps because the average developer feels more removed from the development of those?), but as you pointed out, it does occur.

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.
mszcz·vor 4 Jahren
I don't think that having two different count()s with different edge-case behavior is the way it should've been improved. If someone used the method incorrectly in the past it's part their fault for writing it incorrectly and part PHP's that it didn't fail (and "fail" is also kind of a stretch since the behavior was described in the docs IIRC).
EB66·vor 4 Jahren
Some of the major criticisms most frequently leveled at PHP relate it's convoluted history, the random ad hoc nature of their built-in functions, the inability to enforce types, overly flexible/dynamic, etc all of which can contribute to, among other things, disorganized code.

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.
thinkindie·vor 4 Jahren
If you upgrade without proper testing you are the only one to blame. Seems like that blaming PHP is just an excuse for poorly managing language upgrades.

PHP has one of the best track records for retrocompatibility, this is really the worst thing you could pick to blame PHP for something.
cryvate1284·vor 4 Jahren
Does PHP say it follows SemVer? I don't know as I don't use it but Python doesn't.
johannes1234321·vor 4 Jahren
For the most part. However one person's bug is another person's feature and given the huge number of PHP users, where many aren't formally trained developers the ways in which PHP is (ab-)used is manifold. Thus sometimes things slip through as Bugfix, which then annoy people. But over recent times PHP got a lot better (maybe since I'm not involved anymore)
[deleted]·vor 4 Jahren
cies·vor 4 Jahren
Totally agree. This is beyond taste or preference.

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.
berkes·vor 4 Jahren
For me, a "beginner friendly language" has these properties:

* 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.
magic123_·vor 4 Jahren
While I agree on your three points, I don't think I would recommend Rust to a beginner developer.
berkes·vor 4 Jahren
Me neither.

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.
syshum·vor 4 Jahren
#2: Strict Programming lang's. I often seen frustrate new programmers, specially young new programmers making them want to give up on programming all together so I don't know if I would call that beginner friendly, I certainly would not call rust beginner friendly

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
cies·vor 4 Jahren
If you want to learn programming, knowing how to use type systems is valuable skill from day one.

For children see this (very different objectives indeed):

https://www.rollapp.com/app/kturtle
lbriner·vor 4 Jahren
You are right of course. The thing that many people miss is that learning isn't just one thing from, say, Hello World to a fully fledged application but it involves learning diferent types of things in different orders.

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.
syshum·vor 4 Jahren
While I can understand that approach, I do wonder if my origin to programming is common or not. I did not get in to programming to become a programmer.

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
berkes·vor 4 Jahren
Like sibling comments mention, "beginner" is a broad definition.

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.
lowwave·vor 4 Jahren
> Same can be said (and to me is verrrry true) fro JavaScript. Not if you use JS like Scheme: https://www.crockford.com/little.html

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.
mkdirp·vor 4 Jahren
JavaScript: the language that can barely understand itself is better than PHP! The language, where JetBrain's IDE (arguably one of the best IDEs when it comes to understanding languages, consistently better than any LSPs among other things) can barely understand it fully, is better than PHP! The language that has consistently added new features, but have yet to fix horrible messes of legacy design.

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.

[0] https://www.destroyallsoftware.com/talks/wat
infensus·vor 4 Jahren
It can't fix its legacy design for backward compatibility reasons in browsers
cies·vor 4 Jahren
The linked talk is soo true and so hilarious.
conradfr·vor 4 Jahren
I guess it's a matter of preference because I find writing Javascript tedious, the forced async when not needed, or that for some reason Node doesn't give me a line and a description when I make a mistake, it just ... fails?
nesarkvechnep·vor 4 Jahren
Elixir is one such language for beginners.
pooya72·vor 4 Jahren
Also a lot of the positive changes were do to the efforts of Nikita Popov[1] who has now left. It's led to the creation of the PHP foundation.[2] I haven't kept up to date with the foundation's efforts.

[1]:https://www.npopov.com/aboutMe.html

[2]:https://blog.jetbrains.com/phpstorm/2021/11/the-php-foundati...
Darmody·vor 4 Jahren
Nikita is a beast, one of the smartests guys around.

I wish I was half as smart as he is.
medv·vor 4 Jahren
PHP versions don’t follow semver.

And yes, it’s ok. Semver not a silver bullet.
SergeAx·vor 4 Jahren
PHP doesn't guarantee backward compatibility between minor version. It is the way things are in PHP since 5.x, when Semver wasn't even a thing.
cletus·vor 4 Jahren
I assume then that you disqualify Python for the same reason?

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.
faho·vor 4 Jahren
>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.

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.
[deleted]·vor 4 Jahren
dotancohen·vor 4 Jahren
I've upgraded quite a few PHP systems, and 7.2 was the major stumbling block that I've seen for most projects. Which "changes the semantics of functions between minor versions" are you referring to? In the 7.0 update there was the changing of order that e.g. $foo[bar]->boom[baz] would be evaluated, but obviously that isn't your complaint.
mrunkel·vor 4 Jahren
https://getrector.org/
jonwinstanley·vor 4 Jahren
PHP is actually a really decent option these days. And several libraries and frameworks built around it are flourishing.
cies·vor 4 Jahren
> And several libraries and frameworks built around it are flourishing.

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?
Ronsenshi·vor 4 Jahren
I'm not the OP, but I have plenty of comparative experience working with Python and JS on the backend (node) and I find PHP to be a very decent option compared to those two.

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.
cies·vor 4 Jahren
So compared to JS and $DYNAMICALLY_TYPED_LANG, PHP is "decent these days".

These languages all suffer from very similar problems.

Compare to C#/MVC.net, Kotlin/whatever, Go, Rust to get something noteworthy.
9dev·vor 4 Jahren
Happily!

- 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.
thinkindie·vor 4 Jahren
At least for Go and Rust, they have a much steeper learning curve. If you are a startup with limited funds you are not able to target engineers workings with those languages.

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?
norman784·vor 4 Jahren
> At least for Go and Rust, they have a much steeper learning curve.

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.
mkdirp·vor 4 Jahren
> At least for Go and Rust, they have a much steeper learning curve.

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.
FinalBriefing·vor 4 Jahren
Laravel and its ecosystem is really great. I used to hate PHP, but now I find it quite enjoyable, at least in the realm of building websites.

If you stick to modern versions and frameworks, it's a much different experience from PHP 8 years ago.
jonwinstanley·vor 4 Jahren
The main comparisons I have are building sites with Ruby/Rails and doing JS front ends attached to REST APIs. All three types of project have their own pros and cons.
cies·vor 4 Jahren
The fair comparison: PHP/Laravel to Ruby/Rails...

How is PHP/Laravel better? I'm of the opinion it loses hard in every aspect.
heurisko·vor 4 Jahren
I'm more of a fan of PHP/Symfony rather than PHP/Laravel.

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.
aarondf·vor 4 Jahren
I think one of the key things about Laravel is that the creator, Taylor Otwell, is only focused on Laravel. Imagine if DHH didn't ever have Basecamp (or 37 Signals) and only focused on Rails and the Rails ecosystem. The Laravel team now has several full time employees working on making the entire Laravel experience as painless as it can be.

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.
ramesh31·vor 4 Jahren
>How is PHP/Laravel better? I'm of the opinion it loses hard in every aspect.

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/...
cies·vor 4 Jahren
> PHP, if done properly, is a really great choice nowadays.

Same for Ruby. I found them both slow compared to compiled to native langs.

JVM is also slow (especially startup)
jensensbutton·vor 4 Jahren
Ruby allows you to do even more stupid things than PHP does. It's also slower.
jacquesm·vor 4 Jahren
There is one aspect where it wins hands down that trumps almost every other concern that you might have: availability of developers. This is a hard problem to solve.
aeonflux·vor 4 Jahren
Raw number of developers doesn't matter at all. The ratio of offers to developers out there determines how easy the hiring actually is. I've tried to hire some quality PHP developers and it's as hard as Ruby/Python if not harder. First thing is, that you always get all the Wordpress people, who fixed one plugin and claim to have 10 years of PHP experience. Then you have to filter out all the 10 YoE who actually have 1 YoE done 10 times. For some reason all this is less of a problem in less popular stacks.
jacquesm·vor 4 Jahren
It does if the number is '0' vs 'some'. It usually depends on how and where you do your hiring. For those that only want to hire local developers it is very well possible that there are no local Rubyists, it is also possible that it is the other way around.

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.
cies·vor 4 Jahren
A good dev with only PHP skills becomes a better dev when he/she has other experiences. Ruby or Kotlin would not be off by too much. In my experience they productive in days and are up to speed in a few weeks.

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.
jacquesm·vor 4 Jahren
I'm not religious about languages, I probably used to be, but I grew up and grew out of it.

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.
cletus·vor 4 Jahren
The best features of PHP are:

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.
Darmody·vor 4 Jahren


    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.
zzt123·vor 4 Jahren
Aren’t fibers designed from the perspective of usage in underlying libraries, rather than something for everyday end users in the fashion of async/await?
Darmody·vor 4 Jahren
Nothings forbids you to use them directly but yes.
sdze·vor 4 Jahren
Correct.
psychoslave·vor 4 Jahren
Actually, that make me remember statements of Linus Torvalds on Git at Google Tech Talk Conference:

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-...
omgitsabird·vor 4 Jahren
There are a plethora of articles for "foo best practices" or "bar done right".

I feel like you are stretching a quote to fit a premise that doesn't match the context of this thread or article.
psychoslave·vor 4 Jahren
I didn’t mean to stretch anything, that just the immediate thing that popped in my mind when I red "PHP – The Right Way".

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.
tored·vor 4 Jahren
Funny considering Linus Torvalds believes that C is the best since sliced bread.

https://www.google.com/search?q=c+the+right+way
pas·vor 4 Jahren
He seems pretty chill about Rust, maybe even positive.

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.)
akie·vor 4 Jahren
(2)
rbanffy·vor 4 Jahren
I totally expected it to be a troll site. It's actually sensible advice.

But, really, I suggest using other tools. We have nicer tools now.
unfocussed_mike·vor 4 Jahren
I don't know that many nicer tools than Laravel, to be fair.

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.
BafS·vor 4 Jahren
You should also have a look to api-platform (https://api-platform.com/), it's based on Symfony and you can create Rest or GraphQL APIs with ease.
unfocussed_mike·vor 4 Jahren
That does look interesting.

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).
conradfr·vor 4 Jahren
Or don't, if you have a business data model that is more complex than a hello world.
that_guy_iain·vor 4 Jahren
> But, really, I suggest using other tools. We have nicer tools now.

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.
mtberatwork·vor 4 Jahren
> Downside JVM is a Resource hog

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.
that_guy_iain·vor 4 Jahren
> 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.

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.
StreamBright·vor 4 Jahren
We use Asp.NET and it is a giant surprise how good it is. We are unix ppl, Linux & MacOS so not a MS shop at all. We deploy to on-prem and AWS so no Azure.
zidad·vor 4 Jahren
Same here, the latest asp.net is definitely one of the best performing options out there (maybe except rust in this list), and C# is a great general purpose language to code in (despite the legacy that's in there, like the reflection going on in the framework. unfortunately).
cies·vor 4 Jahren
Kotlin + IntelliJ is a neat mainstream option too. For those preferring a bit less legacy.
that_guy_iain·vor 4 Jahren
It's been so long since I've done ASP that it just when .NET was coming out. I would be interested in checking it out nowadays. WHen I last used it all the cool features were heavily coupled to MS products, is that still the case?
StreamBright·vor 4 Jahren
Not at all. We actually use it from F# with Falco. I am not sure which features you are interested in particular but the ones we like are the basic HTTP handling (requests, responses, etc.), a high performance HTTP server (Kestrel) and we use Falco's html engine as well. On the top of that there is a decent authentication and authorization solution.
dotancohen·vor 4 Jahren
Do you deploy to Linux images on AWS?

I'm actually very interested in your dev setup. Do your devs use Linux machines? What IDE?
StreamBright·vor 4 Jahren
Great questions. I am going to write a detailed article about it because you are not the first person asking these.

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.
dotancohen·vor 4 Jahren
Terrific, thank you!

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?
StreamBright·vor 4 Jahren
Yes I am posting it there. Probably after a bit of a design update.
berkes·vor 4 Jahren
Java, .net, C#, typescript (not my favorite) are all commonly and often used for Web Development.

They are sane languages with large ecosystems and solid frameworks for web-dev.
that_guy_iain·vor 4 Jahren
The question is not can you use something else, it's are they nicer/better tools to work with. I haven't for example seen many things that can honestly compete with WordPress. When it comes to eCommerce, not many systems can compete with Magento/Spryker/Sylius. The list goes on. PHP is a top player in web development while being one of the most hated languages for a reason.

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.
berkes·vor 4 Jahren
> I haven't for example seen many things that can honestly compete with WordPress.

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.
that_guy_iain·vor 4 Jahren
The fact you're talking about building a payment service provider in a CMS kind of tells me this isn't a conversation worth continuing.
Nextgrid·vor 4 Jahren
I have seen something similar to a payment provider being done in Wordpress. The only silver lining is that the ledger was technically maintained by a third-party and WP was just the frontend to it.
berkes·vor 4 Jahren
Me too. And I've seen CRMs built in WP, eCommerce, an auction marketplace, financial dashboard, and so on. But, indeed, processing financial transactions through WordPress is amongst the most scary things I ever saw in computing.
berkes·vor 4 Jahren
Sorry for not being more clear.

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.
dotancohen·vor 4 Jahren


  > 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.
mschuster91·vor 4 Jahren
> The language itself, the downsides are very limited and the main one that remains valid is inconsistency of function parameters.

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.
xigoi·vor 4 Jahren
Sure, auto-completion makes the code easier to write. But you can't make it easier to read.
that_guy_iain·vor 4 Jahren
Jetbrains shows you the name of the parameter while reading so that part is reasonably easy
inoop·vor 4 Jahren
> Downside JVM is a Resource hog

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.
dotancohen·vor 4 Jahren
If you're conversing with someone who believes that the JVM is a resource hog, then you are likely conversing with someone with decades of experience. I would phrase my opposing viewpoint in a more respectable manner, as you might have a lot to learn from someone like that.
inoop·vor 4 Jahren
> If you're conversing with someone who believes that the JVM is a resource hog, then you are likely conversing with someone with decades of experience

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'?
dotancohen·vor 4 Jahren
I no longer think that the JVM is a resource hog. In fact I implied that it was an archaic mindset by suggesting that someone who thinks so has been decades in the industry.

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.
inoop·vor 4 Jahren
> Even my preferred IDE, the Jetbrains suite which I love, are resource hogs

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.
that_guy_iain·vor 4 Jahren
> 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?

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)
inoop·vor 4 Jahren
> the JVM needs to be well tuned

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?
that_guy_iain·vor 4 Jahren
> 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.
powerlogic31·vor 4 Jahren
lpcvoid·vor 4 Jahren
I, for one, would chose PHP8 over Javascript all day, every day. And there seem to be millions like me.
rbanffy·vor 4 Jahren
Well... I wouldn't recommend JavaScript. TypeScript is much nicer and removes a lot of the JS pitfalls.
sdevonoes·vor 4 Jahren
And pulling ~67 dev dependencies just to be able to transpile TS to JS? No thanks.

https://www.npmjs.com/package/typescript
0x142857·vor 4 Jahren
This comment shows perfectly that people has no clue what they're talking about, these dev dependencies will never be pulled into your project, they're just for typescript's own development.
Ginden·vor 4 Jahren
> these dev dependencies will never be pulled into your project,

Please, don't ruin "JS bad" thread with facts. It's rude.
Loeffelmann·vor 4 Jahren
Do these dependencies actually matter when you deploy or are they just used for the actual compiling?
El_RIDO·vor 4 Jahren
If they are required for the compile and someone manages to get something malicious into them, they can certainly affect the produced/deployed artifact.

See Ken Thompson, Reflections on Trusting Trust, 1984 https://www.cs.cmu.edu/~rdriley/487/papers/Thompson_1984_Ref...
cardanome·vor 4 Jahren
Typescripts has an insanely complicated type system (at least for the low level of type safety you get), is dog slow to compile and has cryptic error messages.

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.
azangru·vor 4 Jahren
> Typescript ... has cryptic error messages.

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?
cardanome·vor 4 Jahren
Have you ever used Elm or Rust? Maybe you expectation of how decent error messages should look like is just lower.

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.
azangru·vor 4 Jahren
> 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?
cardanome·vor 4 Jahren
Actually no. Rust will teach you.

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.
9dev·vor 4 Jahren
Hah, let me just chime in with a recent TS error that almost drove me nuts[1]:

  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.

[1]: https://stackoverflow.com/q/67397978/2532203
azangru·vor 4 Jahren
> Would you have figured out that the solution to the problem was to omit the - factually correct - return type of the method?

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.
drran·vor 4 Jahren
Use JS + JSDoc comments with types + TypeScript to check types. No compilation step, but code is type safe.
tored·vor 4 Jahren
TypeScript is nice, the nodejs community is not. It is a shame that such a nice language as TypeScript is stuck in such horrible community.
mradmin·vor 4 Jahren
Can you give some examples of why the nodejs community is not nice?
tored·vor 4 Jahren
Perhaps ecosystem is a better word than community.

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.
wraptile·vor 4 Jahren
As someone who had to learn a bit of PHP recently, I really don't see why would anyone pick it up these days other than vendor/business lock in. Laravel is great but there are hundreds of equally as great frameworks on dozens of more moderns and better though out languages: go, python, nim, ruby etc. A bunch of useful functions expanded into the default namespace is no longer that special.
ihateolives·vor 4 Jahren
> there are hundreds of equally as great frameworks on dozens of more moderns and better though out languages: go, python, nim, ruby etc

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.
bayesian_horse·vor 4 Jahren
I guess sometimes you are forced to use tools you'd rather not.
tored·vor 4 Jahren
What tools? What server language today except PHP (and its forks) is actually designed for the web and works as the web was intended?
onion2k·vor 4 Jahren
What server language today except PHP (and its forks) is actually designed for the web and works as the web was intended?

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.
simion314·vor 4 Jahren
> 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.
onion2k·vor 4 Jahren
CoolLang sounds a lot like JS.
simion314·vor 4 Jahren
There are more languages not only JS, with small standard library and the community offers multiple packages for same thing(like more packages for json) but you install them at your own risk - though this weaknesses are promoted by Cool.lang fanboys as features.
tored·vor 4 Jahren
> That part of any language can be filled out with a framework quite easily

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.
capableweb·vor 4 Jahren
> 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).
berkes·vor 4 Jahren
> That has always been the goal of PHP, to be a web framework in itself

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
capableweb·vor 4 Jahren
We're saying the same thing :) Templating language (for the web) and handle forms (on the web) makes PHP a web-language first and foremost. That's also the impression I get from reading the following section from the Wikipedia page you linked:

> 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.
berkes·vor 4 Jahren
I think I focused too much on the word framework, which is a vague word, and probably means a lot of different things depending on perspective.

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.
capableweb·vor 4 Jahren
Yeah, that's true, my bad for being a bit ambiguous. I always saw PHP as a framework on top of C for writing web applications, which can also be called a language.

But no harm done, thanks for clarifying yourself :)
rbanffy·vor 4 Jahren
> With PHP, it's literally one-line of code.

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.
capableweb·vor 4 Jahren
> 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.

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 :)
berkes·vor 4 Jahren
Continuing on Rails: It's suprising how little Rails does with the web. Rack is the layer handling the HTTP stuff. Which then sends its requests to ActionDispatch, which calls the correct ActionRouter.

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.
azangru·vor 4 Jahren
> and Rust web projects use Poem

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?
rbanffy·vor 4 Jahren
> What server language today except PHP (and its forks) is actually designed for the web and works as the web was intended?

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.
sgjohnson·vor 4 Jahren
Nobody in their right mind has put actual logic inside templates when doing PHP for a while now.

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.
369548684892826·vor 4 Jahren
Razor lets you write C# inside templates.
chinathrow·vor 4 Jahren
> But, really, I suggest using other tools. We have nicer tools now.

Citation needed.

For folks not wishing to switch frameworks and tooling every year, you can get a lot done with PHP.
rbanffy·vor 4 Jahren
> Citation needed.

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.
capableweb·vor 4 Jahren
Comparing PHP to using wood and nails feels misguided. PHP is a web framework, which makes it easy to handle writing web applications. It's more like using Python for web stuff is wood and nails, while using PHP is using wood and a nailgun when you need to stitch planks together (or something like that). PHP is made for the web, and you can tell by the specialization of the API interface it offers, which ships with most things you need for doing web stuff, while most languages does not. Getting the body from a POST request is trivial in PHP, while in most language you'll use a library for that, or write a bunch of code.
rbanffy·vor 4 Jahren
The nail-gun is a surprisingly good analogy. There are lots of other things you can do with a hammer, from hammering nails, to shaping metals, to removing nails, to getting things unstuck. With a nail-gun you are kind of limited on what you can do.
fraktl·vor 4 Jahren
throwtcp5327·vor 4 Jahren
Just wanna dump a bunch of similar PHP sites you might find useful:

(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
faho·vor 4 Jahren
PHP is still full of awkward decisions.

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. "

[1]: https://www.python.org/dev/peps/pep-0538/
pas·vor 4 Jahren
It seems awkward, but it's not. It picks picks a deterministic default instead of a "whatever you have in your OS environment".

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!
thriftwy·vor 4 Jahren
But what's the point?

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.
Isinlor·vor 4 Jahren
PHP share-nothing architecture is awesome. It's amazingly simple and it scales to arbitrary size.
masklinn·vor 4 Jahren
Complicated frameworks means the “shared nothing architecture” is unusable and you have to use fcgi/fpm to get acceptable performances out of your website.

At which point there’s little difference from <everything else>.
ihateolives·vor 4 Jahren
"Acceptable" is different for different folks. I don't understand the general sentiment of either you have enterprise level performance or it's a fail. Not everyone is building next Facebook or Amazon and yet most developers think that they are and vastly overestimate their needs. Also most hosting provides already have fpm configured for you and if you need to do it yourself for your VPS then it's not complicated.
TazeTSchnitzel·vor 4 Jahren
What's wrong with FastCGI? PHP provides a CGI-like model regardless of which interface to the web server is actually used.
heurisko·vor 4 Jahren
As I understand it, adding fpm doesn't change the "shared nothing architecture" as each request is isolated from the other. There is no application server that can potentially store state between requests.
bayesian_horse·vor 4 Jahren
PHP has a deep history of less than ideal defaults and Tutorials/Examples. This makes scaling a codebase without some kind of framework (even if homegrown) even more of a challenge.

And in my opinion PHP tends to be ugly and less readable by default.
thriftwy·vor 4 Jahren
PHP did not invent CGI and the whole selling point of mod_php was "share-something" architecture.
mschuster91·vor 4 Jahren
For the PHP-side application developer, PHP is in 99% of use cases shared-nothing no matter the hosting environment - CGI, FCGI, FPM, mod_php. The exceptions are persistent socket (database) related, obviously you don't have these in a CGI environment.

The mod_php "share-something" question was always more relevant for ops people.
Isinlor·vor 4 Jahren
Obviously it's share something e.g. session state and database state.

But architecture of PHP applications is simple and it works. I like simple.
cies·vor 4 Jahren
> PHP share-nothing architecture is awesome

There's nothing PHP specific about share-nothing architecture. It's often refereed to as stateless application layer in other camps.
rbanffy·vor 4 Jahren
> 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.

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.
asadkn·vor 4 Jahren
I have used PHP as a replacement for even shell scripts, like perl and python, a lot in the past. The best thing is the very strong standard lib. Everything's built-in. I like node as well, but having to install so many packages just for that one file script is a major annoyance.
thriftwy·vor 4 Jahren
In the mid-00s the main selling point of PHP were shared hostings with mod_php which was a cheap way to host your own web site and database.

Now with the cloud that advantage is utterly gone.
deniska·vor 4 Jahren
Shared hosts are still there, and are cheaper and much simpler to use than your average cloud based deployment. Some even support these new hipster programming languages ruby and python.
JodieBenitez·vor 4 Jahren
"new hipster" programming languages:

Python 1.0: January 1994

PHP 1.0: june 1995

Ruby 1.0: December 1996
deniska·vor 4 Jahren
Sure, but if we're talking about these languages being "socially acceptable" for writing websites, they arrived a bit later to the party than PHP.

Granted, it still happened about a decade and a half ago, so I hoped the sarcasm using the word "new" would come through.
JodieBenitez·vor 4 Jahren
> 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.
sdze·vor 4 Jahren
PHP still has a vibrant ecosystem. 1) cost 2) simplicity 3) scalability

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.
sshine·vor 4 Jahren
I spent the better part of 2021 porting a PHP app to Kubernetes. If there’s one thing PHP is not, it is performant.
heurisko·vor 4 Jahren
PHP is performant compared to other similar scripting languages, and in any case, the database is usually the bottleneck.

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=...
sdze·vor 4 Jahren
Then you will have a lot of fun paying those VMs when you use ruby or python.
pjmlp·vor 4 Jahren
For my tiny website there is nothing that cloud brings other than being more costly.

I have the same access to my shared hosting, and the amount of money per year is peanuts.
hnlmorg·vor 4 Jahren
It very much depends on how code is written. A typical LAMP (style) stack wouldn't be any better on the cloud than it would on shared hosting. But if you can make use of serverless (eg lambda, S3 and/or DynamoDB on AWS) then that's where you'll start seeing some advantages.

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.
tempodox·vor 4 Jahren
Same here. None of my web projects is designed for a larger audience, hence the biggest advantage of my tiny public Linux host is that it has a fixed cost. An HN “hug of death” would bring the respective application server, and possibly the whole machine, to its knees.
systemvoltage·vor 4 Jahren
I am not quite sure if Jamstack has improved anything. I feel like the entire web stack is spinning wheels and hardly progressing.
dgb23·vor 4 Jahren
It's moving somewhere from "not quite there yet" to "substantial, qualitative improvement" as we speak. I'm following what happens in that space with React/Node based things like Next, and Redwood (soon v1.0), and others. The building blocks are there and the integrations get better and better.

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).
cutler·vor 4 Jahren
Most of those cheap hosts served PHP via FastCGI not mod_php.
schipplock·vor 4 Jahren
There is legacy code out there, and I think people are grateful for these frameworks :).
omgitsabird·vor 4 Jahren
> more mature infrastructure and better language

What does this mean?
thriftwy·vor 4 Jahren
PHP is a conceptually awful language. It is created by language amateurs and it shows in many early decisions such as the multiple thousands of built-in functions already mentioned.

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.
omgitsabird·vor 4 Jahren
> created by language amateurs > all of that is gone and they are still stuck with a subpar language

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.
irq-1·vor 4 Jahren
> Right now PHP does not support Unicode at a low level. There are ways to ensure that UTF-8 strings are processed OK, but it’s not easy, and it requires digging in to almost all levels of the web app, from HTML to SQL to PHP. We’ll aim for a brief, practical summary.

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.
WalterGR·vor 4 Jahren
That sure is a big a web page for having no table of contents!

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.)
exikyut·vor 4 Jahren
To answer the immediate question, I had a look and nooope, no <a name="">, not even <a> anywhere, that I could find. However I just (begrudgingly) realized this is somewhere text fragments can shine: https://leanpub.com/phptherightway#:~:text=Getting%20Started

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.
jorams·vor 4 Jahren
I'm not sure what you're seeing, but for me the page starts with a massive ToC. On even smaller screens it turns into a button fixed at the bottom of the screen that opens a ToC in an overlay.
WalterGR·vor 4 Jahren
Hmm… Not sure what’s going on then.
norman784·vor 4 Jahren
I want to like PHP, but it seems that there are so many better/modern alternatives out there, IMHO Go and Rust are the most notable new ones, Go is almost (if not yet) ahead of PHP in terms of community and resources (learning and packages), while Rust still needs a few years to establish (the async issue and few others) and the maturity of the ecosystem, there are no killer solution yet (maybe there will never be).

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).
tonyjstark·vor 4 Jahren
Not sure about your experience with Laravel, but I don’t see how the type system is bad for it. It works surprisingly well for me. With a bit of tooling I get even autocompletions for database fields when using Eloquent. PhpStorm with the (paid) Laravel plug-in are pretty awesome and give me more information during file-editing than for example Xcode.

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.
norman784·vor 4 Jahren
It also could be that the learning curve is steep to get some things done and this was a side project that I wanted to get done. That could have contributed to my bad experience, also I'm not developing in php professionally anymore and sometimes when I want to get shit done, but this time it didn't worked for me.

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 :)

[1] https://github.com/launchbadge/sqlx
pluc·vor 4 Jahren
You didn't try PHP, you tried Laravel.
haolez·vor 4 Jahren
Slightly of topic, but is Hack a thing outside of Facebook? I'm a little thrown off by the confusing standard library of PHP, but I don't know if using Hack instead would solve more problems than it creates.
TekMol·vor 4 Jahren
My problem with PHP is that it solves the issue of code reuse the wrong way round.

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.
raytube·vor 4 Jahren
There is 'use as'.

But it is infuriating having to namespace your code when a folder name/heirarchy could do.
agumonkey·vor 4 Jahren
Doesn't that shield you from FS/OS impl though? I often found it the only reasonable explanation (for java too)
raytube·vor 4 Jahren
I still haven't worked out how to phar.

Is this problematic for archive distribution?
lmz·vor 4 Jahren
Other languages? It's the same kind of namespacing that Java or C++ has.
tored·vor 4 Jahren
Namespaces in PHP are totally fake, they are not real as it is in C++, where you can actually store data within them.

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.
TekMol·vor 4 Jahren
Nice.

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.
tored·vor 4 Jahren
> Is the strict_types dance necessary for this?

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.
_def·vor 4 Jahren
You can `use Illuminate\Mail as Mailer` if you want
TekMol·vor 4 Jahren
That is not what I mean.

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.
ainiriand·vor 4 Jahren
You can hope all you want but you won't be able to submit any duplicated namespace to Packagist.
TekMol·vor 4 Jahren
That is another consequence I don't like about the quirky namespace approach. It collects more and more problems like a ball of dust that gets bigger and bigger.

The consequence you mention is that one depends more and more on tooling and services.
CR007·vor 4 Jahren
Did you actually get these issues in a real use case? I've been developing PHP software for +15 years and I never had this namespace dilema.
TekMol·vor 4 Jahren
But you suffer the indirections caused by the fat stack that is needed to deal with the missing import system.

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.
CR007·vor 4 Jahren
The fact that composer comes with an autoloader doesn't means that you have to autoload everything.

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?
TekMol·vor 4 Jahren


    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.
ihateolives·vor 4 Jahren
Web applications come in all shapes and sizes. If you have an application that just mediates data from database and exposes API to frontend then for couple of endpoints you don't even need router or any other packages, PHP has lots of stuff baked in. You just check if the request is GET/POST/PUT/DELETE/PATCH, work with data, output a header 'Content-Type: application/json', send the data and be done with it. Or output a html template with data or whatever. Or you can not use templates and mash it all together in PHP which already is a templating language. You can do it as simple or complicated as you need.

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.
CR007·vor 4 Jahren
Nope. I don't use these frameworks. But thanks for trying to assume how php is on 2022 and how all php devs work.
TekMol·vor 4 Jahren
How do you build web applications these days?
captn3m0·vor 4 Jahren
The autoloader in composer offers several alternatives, and while all of them are namespaced per convention - nothing stops a project from deciding to write their own - something super easy in PHP but impossibly hard in other languages.

I find PHP packaging and dependency management to be painless compared to both Python/Ruby.
rbanffy·vor 4 Jahren
Java solved this by using domain names as unique identifiers. I can use com.banffy and be sure only a complete a*hole would make a package in this space.
jwdunne·vor 4 Jahren
This is roughly PHP’s approach. In this case, Illuminate is the vendor prefix and Mail is the package name. This often but not always corresponds to the rules around the composer package name, which would be illuminate/mail in this case.

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).
captn3m0·vor 4 Jahren
I actually prefer auto-loading, which lets you iterate through a package manager much easier/faster - PHP iterated through PSR-0[0] before landing on PSR-4[1], and you can always build your own (which is what most frameworks pre-composer were doing).

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...
jwdunne·vor 4 Jahren
Yeah, I prefer an actual module system over PHP namespaces plus autoloader. It feels like a hacked on module system tbf. BUT I do get lots of real work done using namespaces and a PSR autoloader so it works.

I do wish they would extend auto loading for standalone functions and constants though.
[deleted]·vor 4 Jahren
ainiriand·vor 4 Jahren
The way I see it is that you alias the import mail as mailer. You hope there are no other libraries called mail in your import path. PHP fixes that by requiring all libraries called mail to be dependent on their own namespace so that there will be no collisions.

I think that neither do make assumptions on how the code is called when used, only one is preventing name collisions.
TekMol·vor 4 Jahren


    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.
sandruso·vor 4 Jahren
Isn’t this same thing? Your dir in python structure is dictating the namespace isn’t it?
TekMol·vor 4 Jahren
The dir structure is defined by me.

Namespaces are defined by the 3rd party developer.
ainiriand·vor 4 Jahren
That is not exactly true, you can tweak composer to put dependencies anywhere you want them. What I feel is that there is a minor inconvenience, as many other languages have, and you try to build a case to bring down a whole ecosystem.
leegraham·vor 4 Jahren
That example would become `use Stuff\Mail as Mail1` and `use Tools\Mail as Mail2` in PHP. What's the difference?
TekMol·vor 4 Jahren
The difference is that in PHP, the developers of "Stuff\Mail" and "Tools\Mail" would have to define "Stuff" and "Tools" as the namespace for their code.

In Python, they don't have to do anything. The project that uses the code decides.
[deleted]·vor 4 Jahren
fraktl·vor 4 Jahren
ofrzeta·vor 4 Jahren
Updated in January but not really up to date. It doesn't mention union types, the nullsafe operator, matching expressions and a lot of other features you can find here: https://stitcher.io/blog/new-in-php-8

Maybe not everything is "the right way" but at least the nullsafe operator is, I think.
[deleted]·vor 4 Jahren
xet7·vor 4 Jahren
I'm trying to learn https://haxe.org , so that if some target language does not work, I could use some other target language. Currently I have hard time updating to newer version of Node.js, dependencies etc. I tried to code something with PHP 8.1 directly, but I presume any following update could change syntax etc.
mapmap·vor 4 Jahren
Is there a page like this for c# dot net?
jbverschoor·vor 4 Jahren
Why not install using asdf ?
porker·vor 4 Jahren
When I looked ~ 2 months ago, PHP via asdf looked buggy and abandoned?

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.
cortexio·vor 4 Jahren
marcusfrex·vor 4 Jahren
(3)
trowawphphate1·vor 4 Jahren
nalekberov·vor 4 Jahren
The reason why people now care about PHP is that, decades ago they thought PHP would the right way to develop projects, now they are stuck, because they cannot get rid of PHP any more. If you look at any well grounded projects, they try to avoid PHP at all cost. Only handful amount people are responsible for core development. 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.

There are tons of tools to get things done, PHP is one of the worst ones.
cardanome·vor 4 Jahren
> The reason why people now care about PHP is that, decades ago they thought PHP would the right way to develop projects, now they are stuck

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.
nalekberov·vor 4 Jahren
> I worked on many greenfield projects in recent year where the conscious choice was made to use PHP.

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.
cardanome·vor 4 Jahren
> What kind of greenfield projects were they, and who was making those conscious choices? Without context it's just non-sense.

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.
hotz·vor 4 Jahren
A poor developer can make any tool look bad.
nalekberov·vor 4 Jahren
sure, but why would you use poor tool in the first place?
archerx·vor 4 Jahren
What is your experience to make such ignorant statements?
nalekberov·vor 4 Jahren
I will just leave these here:

https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/

https://software-gunslinger.tumblr.com/post/47131406821/php-...
archerx·vor 4 Jahren
Ah I see, you partake in cargo cult development. Thank you for elaborating and have a good day.
nalekberov·vor 4 Jahren
check, next PHP fan boy please.
sgjohnson·vor 4 Jahren
Those articles are 10 years old.
bowersbros·vor 4 Jahren
That first article is a decade old.
xigoi·vor 4 Jahren
The article has been updated over the decade. It mentions which things have been fixed — most of them haven't.
kgeist·vor 4 Jahren
I used to hate PHP with passion myself (having read those articles too) before I had to take on a large project which used modern practices (PHP 7+, latest Symfony) and I can say it's been a surprisingly smooth sailing so far, most of the time you use nicely designed abstractions over the core APIs provided by the framework (or its modules) and don't use built-in functions directly. The actual annoyances I notice everyday are things like inconsistent argument order in array_* functions (people prefer to use them directly), but you quickly get used to it and there's not that many of such functions in day-to-day work. What you usually do is generic stuff like defining models, writing controllers etc. and most of the time it doesn't feel much different from other enterprisey languages I've used such as C# or Java. From time to time you have to use some arcane PHP function because the framework doesn't provide it for you but there's a custom, at our company at least, to wrap such functions in nice utility classes once and forget they exist.