One of the underappreciated pros of php for web development is its execution model, it's fault tolerant by default and shares little memory across requests. This kind of makes sloppy programming far more tolerable in php than in other platforms.
In effect this has an impact on performance but it also helps in ensuring that a bad request can't blow out the whole application from serving other requests like is common in platforms like nodejs where you need to be extra careful.
Needless to say this makes php becomes quite viable for production envs, and prevents a whole host of issues that need expertise and careful programming to fix.
I'm thankful to have started programming in PHP when I first started doing web work for this reason. Shared mutable state is (almost always) bad and virtually everything I've built after that (on any stack) follows similar rules around per-request isolation because of the patterns PHP instilled in me.
Not only does this reduce (1) the likelihood of correctness issues, but it also dramatically reduces (2) deployment complexity because you don't need to migrate a bunch of in-memory state distributed across web backends. Your servers should all be considered dispensable.
In 2020, I tend to bias towards things like AWS lambda for this reason (for low volume applications). By default, there's no guarantee on the lifetime of the serving process and any unhandled exception recycles the process so you're never in an unknown (bad) state. There are of course performance downsides to this (particularly when it comes to pooling connections for things like Postgres), but once you figure that out things are generally smooth sailing.
What I miss about PHP is that it was possible to put a file in a folder and use it instantly.
If you want to quickly do something without diving into frameworks the tooling was easy to setup and rarely fell apart, if ever. There are not many moving parts, you usually have a web server that is very solid and comes with an installer that you hit next next next. Then you have a database server, usually MySQL. Sometimes you would need an extension to work with images, you put it in place by editing an .ini file.
And yet, I find that PHP apps tend to be quite performant, compared to say Java or Rails (I don't know about node, maybe not compared to node). But I'm not a PHP developer, this is just my impression. And the complaints you hear about PHP, I seldom hear performance. No?
It varies considerably. If you write the kind of simple PHP pages which gave it that reputation, it's almost always going to be limited by I/O. If you use a framework which encourages enterprise-style apps with hundreds of includes and object hierarchies which would make a J2EE developer weep, even the opcode cache won't be enough to get back to that spot. I don't follow it enough to see if this passing away niw but there was definitely a sizable chunk of the community which really thought that Real Programmers™ didn't write simple code.
i did a simple test between PHP, Java, Elixir and Haskell for fun (with a full payload/page that represents my problem domain) - PHP was within +/-10ms of the others for the same payload/template process. Guess which one was the slowest?
if you do something in a naive way, PHP performance can tank pretty severe - but that's more down to the developer implementation rather than a shortcoming of the language itself
If you mean persistent databases or caching like Redis, it's still much easier to accidentally reference a global pointer due to a programming error than accidentally put something in a cache store. All systems need some sort of persistence, this is true for other languages as well.
Like others have mentioned, there is no such thing in PHP. Each request is handled individually from a blank slate and the context is destroyed when the request finishes.
the largest performance issue i've come across with the execution model is that connection pooling is...well, pretty crap. opcache handles most of the other interpreted woes rather well.
Are you talking about connection pooling to services like databases and caches? Most extensions implement it (pgsql and I think MySQL) but you need to configure it. I’ve also use a local nginx proxy to pool the connections.
It's becoming kind of an Enterprise language [1]. Don't get me wrong I think PHP is getting cooler, hopefully everybody catches up and the fact that You can have a shared hosting for pennies run Your PHP code really puts it at an advantage compared to others.
It tried for decades to be one with Doctrine, Symonfy and co, trying to copy the worst of Java EE with every single possible design pattern implemented in these frameworks, XML configuration files and co... The problem is no generics, no private packages makes PHP OO a horrible mess compared to Java (or C#).
I agree with you. Symfony and composer in general has just turned our code base into some kind of fugly java like monstrosity.
When I used composer the first time I really enjoyed it, that project also used Silex a minimalistic symfony2, which I also really liked. But what I found out is that in general it is really terrible to be dependent on others, as Silex was dropped by Potencier and my project is left in limbo, sadly. Its very sad because its one of the coolest things I ever worked on, and its still in use today many years after. But I am worrying that some time in the feature, a vulnerability or problem with Silex comes up, the company will have to rewrite the project completely some day.
I worked alot with Drupal7, absolutely hated it mostly because the hook system was hard to remember and performance of Drupal7 in general was absolutely terrible. Then I tried Drupal8 and though some changes are welcome, some stuff are just so god damn complicated, a task that would have been as simple as a few lines of code becomes pages of boiler plate, EventSubscribers and YML config files.
PHP used to be a good choice because it was rapid application development on crack cocaine, developers were cheap and diverse in skill and background.
I still think there is SOME use for PHP, I personally like it for shell scripts mostly because im so familiar with it. I used it alot the past 10 years for making stuff fast for friends and personal use I guess its also a decent beginner language for web development, though javascript would be higher on my list today because of the obvious front end relation.
I have been bitten too by the abandoning of silex and symfony becoming more and more like a complex java beast. The zend framework 1 was once good with a simple abstraction but they turned java like too.
Nowadays i develop in laravel which is breeze to work with. A simple framework and you can choose whether to use it as simple as silex, full blown like symfony or somewhere between. I started using it like a silex with controller classes and migrated more and more to the symfony way, but still its really easy understandable for any new developer.
That's what baffles me with PHP. Instead of building on PHP's unique capabilities, they try to become more like Java. When PHP was and is quite successful as server-side language for HTML templating, rooted in embedded PHP triggered from SGMLish processing instructions in otherwise static HTML. It's only that they made such a hack job without context-dependent, HTML-aware escaping, making it a primary vector for injection attacks.
It was because every developer in the West was taught that inheritance based OOP was the one thing to rule them all.
And that unfortunate school of thought created the Java mythos that spread to many languages, not only PHP, eg JavaScript (everyone trying to write inheritance based OOP in a prototype based language).
Few years ago the mythos changed somewhat to every programming language should be functional.
Thus it is not a specific PHP problem, it is common problem of trend sensitivity in programming culture.
And the funny thing is that much of the critique against PHP, like in this thread, is in the form of "why isn’t PHP like the other programming languages?"
But agree PHP should go it’s own way, it has much to contribute to the world still and it feels like it has started to create its own path again.
> It was because every developer in the West was taught that inheritance based OOP was the one thing to rule them all.
>
> And that unfortunate school of thought created the Java mythos that spread to many languages, not only PHP, eg JavaScript (everyone trying to write inheritance based OOP in a prototype based language)
I don't think it's as simple as OOP being bad but rather the culture of complexity that everything had to have deep object hierarchies, layers of indirection and runtime configuration, etc. If you write Python, JavaScript, PHP, etc. classes which don't try to follow the enterprise Java style and only pay for the complexity needed by the problem domain the results are fine.
I think a large part of it was that many people learned not OOP but how the Java standard library and J2EE worked, and internalized the idea that you were trying to produce a reusable abstraction for the entire stack which could be used by unrelated projects without realizing how expensive that kind general framework development is.
Correct, OOP in itself it’s not bad. I use it every day, but I mostly use composition rather than inheritance.
What I was trying to say was that the inheritance based OOP was sold as the ultimate problem solver.
We all remember programming classes with Hello World like examples of Cat inherits from Animal.
Problem is of course that in the real world is never that simple so the inheritance based model turned out many times to be a mess because it was applied to problems where it didn’t fit.
That doesn’t mean that inheritance based OOP has its place, it does, but that is usually in very specific domains.
I totally agree. What I'd actually welcome these days is a web "glue language" which adheres to what PHP wanted to be in the beginning (easy HTML output, one file per page, easy database querying, easy CGI interfacing), but without any OOP bolted on (C-style procedural would be fine), without any of the horrible security decisions, and with strong typing.
It would make a nice counterpoint to all OOP-style web dev languages (Django, RoR, PHP8+framework + routing logic) and all frontend-focused frameworks (React, Vue). Super-simple, super old-fashioned, but rock-stable and easy to kickstart a small website or prototype, and great for teaching (nothing is easier than "drop a index.lang" file in this directory and you have a website).
There's not much in PHP 5/7/8 which precludes just doing some raw db queries and including some templates.
The biggest 'drawback' might be that there's not one name-branch 'framework' which takes this approach (indeed, it's the opposite of 'framework' thinking). But if there was some project that documented/demonstrated 'best practices' for 'non-framework' projects, it might help reduce the "I need a framework because raw PHP is so messy" objections.
1 - security-safe and type-safe from the beginning
2 - none of the additional programming paradigms. PHP wants to be everything in one language. I know you can still use PHP "basics" like that, but it's not going to be easy to find tutorials etc. showing that
The main point I wanted to make was not about the index.php file. In other words, I'd like a PHP3, but a clean, safe, very well-designed one.
It would be impossible to maintain backward compatibility if they made the language HTML context aware. It would make it more difficult to output any non-HTML content type from a PHP script. It would require many new syntaxes (e.g. for outputting variable data in the attribute values of elements, selectively outputting elements or attributes, looping through them, etc). It would also mean the language is tied to specific HTML versions and it would not be able to be forgiving of HTML syntax errors, defeating much of its ease of use.
I am not sure it would have been practical to turn PHP into a strongly HTML aware template language like Thymeleaf for example, while still having it be useful as a general purpose programming language. IMO, the dream of PHP/CFML/JSP/ASP mixing code with templates just isn't realistically possible.
Backward-compat and syntax doesn't have to be a problem. The `<?php ...>` processing instruction can stay as it is, only to be augmented with a new opt-in mechanism based on entity expansion (the fully context-aware templating mechanism built-in to SGML/XML). Eg roughly
<title>bla</>
<?php let x =
"<p>whatever</p>"?>
&x
<div class="debug">
<![ RCDATA [
&x
]]>
</div>
where x is bound to markup checked against permissible elements in the first context (eg rejecting <script>) and escaped into <p>whatever<p> in the second. Rejecting script elements in user or other dynamic content as well as escaping comes for free with regular SGML parsing.
There are many cases that doesn't solve, for example, how can I conditionally decide to either inject an attribute or not inject it using this technique? How do I mix user-controlled text which should be escaped with dynamically generated HTML in PHP strings that I don't want to be escaped? How will scope be managed and can those constants be redefined (not normally a concern in SGML)?
Plus, what makes you expect this opt-in syntax would catch on if people already don't care enough to use HTML-aware template engines?
EDIT: Also, what happens if the static parts of the document aren't syntactically correct SGML? How can you even know if the final output will be syntactically correct SGML until you run all the legacy parts of the PHP code that output directly in the document stream?
Re: conditionals
SGML allows marked sections to have parameter entities as keywords, and recognizes INCLUDE/IGNORE in their expansions:
<!entity % e "include">
...
<![ %e [
will only be included if
e expands to INCLUDE
]]>
Re: mixed user/system text
SGML supports quite restrictive content model exclusions, eg the "-(script)" part below makes SGML reject script elements in main's content anywhere:
<!element main - - ANY
-(script)>
Moreover, you can declare an entity as a so-called data text entity, special chars in which are preserved
Re: running legacy parts
There's no difference to what PHP does now eg just running through the page/template doc until the end, erring out on validation errors?
actually in future versions symfony will move mostly to php based configs instead of yamk, xml. at least parts of internal configs which were xml now are rewritten to php
It's a different culture. They go around the problems differently. Also the way the write programs seems simpler and leaner (composer in mind)... probably not ultra safe but a good enough ratio I guess.
> It's a different culture. They go around the problems differently. Also the way the write programs seems simpler and leaner (composer in mind)... probably not ultra safe but a good enough ratio I guess.
No it's not a different culture, they(enterprise Java and enterprise PHP) both try to force some IoC container everywhere, except PHP is an interpreted language, it doesn't need a IoC container with with XML/YAML configuration files cause there is no long and costly compilation step to begin with...
That's unrelated, you can tell very rapidly how nicer a tool like composer is from most java things of this era; this is entirely cultural IMO.. you can use xml or yaml in fine or absurd ways.
I’ve seen some self-balancing backed priority queues implementations, using some quirks of PHP, that are faster than the C implemented ones and faster than a “standard” implementation. Wall clock time, it’s still O(log n).
Lately I see myself abusing (???) types more often than ever. Before, I'd feel comfortable returning an array of structured data from a function. Now, I'm creating Value Objects to ensure my data is both valid and correctly used elsewhere. Kinda feels nice to get intellisense working too and knowing that the things that I'm trying to do with that VO are valid
> Before, I'd feel comfortable returning an array of structured data from a function. Now, I'm creating Value Objects to ensure my data is both valid and correctly used elsewhere.
Same. I've written some complicated ETL/data transform processes in PHP, and used arrays because the array_* functions are so useful for manipulation.
But keeping track of what keys were available was a nightmare - especially coming back to maintain the system.
Like you I've switched to Value Objects. In many ways it's a pain (the intermediate representation that I'd stick into a new array key and pass to the next transformation - it doesn't belong on any of the objects; and PHP needs the equivalent of the array_* functions for objects) but knowing I can't use the wrong key somewhere makes it worthwhile.
PHP started to enterprise the moment they add PSRs IMO. It was no more a scripting language first. It was also at the clean OO push. Very Java like in a way.
If you are sufficiently motivated, you might look into Emac's "babel" scripts, which can run Python embedded in org-mode files. You could use mod_wsgi in Apache to set your .pml (Python Markup Language, I just made that up) files to be parsed.
I too use php for automation. It has a lot of "built ins" that are always there (reading csv files for example/ json reading), which I find makes things a little easier for a lot of simple things.
if i have to crunch numbers in a script I like R, or Python w/ Pandas
Can a fellow geek knowledgeable in PHP gives me a few pointers?
I have inherited a 12 year old PHP app written by 2 interns. The code was written with Notepad++ (no IDE), no comments except when they copy pasted something from the internet, most variables are single letter and it's the biggest spaghetti bowl I have ever seen.
To add insult to injury I have no experience with PHP (apart from peeking at this code to fix a minor bug here and there). To be fair the app works OK and has done the job for all those years.
This app has never been updated so it's PHP version 4 or 5 I think, it runs on an old Debian 5 VM, it's not facing internet, internal use only. It was supposed to be deprecated last year, but now given our budget (or lack thereof) and the sheer incompetence of our new provider I don't see it happening soon.
Is there a way for me to have an IDE with a kind of "compiler" that would help me convert this to PHP 8 so I can migrate it on a more recent VM?
Of course there's 0 budget for this.
- Make sure you have version control. So easy to do these days, so often forgotten.
- don't think that the steps above must be done in order, right now.
- dkarlovi mentions tests. Start with 1.) smoke tests like simple selenium tests or something like that. You'll find lots of vate towards it if you look and I admit it has issues but for simple projects like this that doesn't change much it should be fine. Of course of you find something better use that.
- one of the most important things about a good IDE is being able to refactor confidently so you can rename variables to something reasonable as you figure out what they really are.
- the book "refactoring legacy code" might be the best programming book I've read.
There seems to be a new version coming out in the next couple of months (ISBN 9780136657125) but I can't tell if it's a new edition or just a redesign.
Yes. Upgrading really old php application (v4? really?) to v8 is such a big step it will need much dedication, so many things changed between 4 and 5 its not easy. And even upgrading 5 to 7 may break so many things. I would not like to switch with him.
> Adding tests for an app with no documentation requires a lot of effort.
code tests yes. Assuming it's a web app, probably not too hard. Get something that records the browser interactions, and do the common tasks people do (log in, click links, make a report, etc). Having general things like that automated to ensure you can run them repeatedly to make sure basic stuff didn't break unexpectedly will help provide some confidence when making changes.
As others said, vscode with php extensions works quite well (you do need a local php install for intellisense to work iirc?)
As for migrating. I wouldn't aim for 8, that's a hell of a jump to make from 4/5 and just getting to 7.x would give you a few years of breathing room https://www.php.net/supported-versions.php .
First goal, get it working on 5.6 without any deprecation errors or notices, that's a good basis for a "legacy" codebase to be on.
From there, the hop to 7.x is mostly changing any mysql_* calls, avoiding the short tags (use `<?php` instead of `<?' and a few other things found by looking at the migration notes here https://www.php.net/manual/en/migration70.php (other version notes available from the menu on that page).
As for tooling, Rector, phpstan and Psalm might be helpful, but might be more trouble than their worth if you've only dipped your toe into PHP development. Rector can do automated refactoring with some code (helpful for the mysql_* function removal/replacement with mysqli_* for instance). phpstan and psalm are static analysis tools that can help find problems or issues with the code.
Final comment, make sure this is in version control so you can track any changes made and have known working versions.
I've spent a lot of my career updating/fixing/replacing aging PHP apps, so here are some pointers:
0. Ignore PHP8 for now. There's much more community support for PHP7, so fix it up to work on PHP 7.4 first.
1. My first task is always to use a code scanner to test if the codebase is PHP7 compatible (or PHP 5.6, or the next version on from whatever you're running). See https://blog.fortrabbit.com/php-testing for an incomplete list (I've used others but haven't got my bookmarks to hand). You'll get false positives but also a good feel for whether there are serious issues.
2. You don't say if it's a CRUD app or an API. If it's the latter: set up a PHP 7.4 box (with a copy of the datastore) and route all traffic to the current production box and to the copy. Save the responses from both and compare they're the same. A simple way to see if the app will work on PHP, and when you find something that's broken, you can fix it, reset the logs, and try again. Hard(er) to do with CRUD, but I have compared the datastore contents before to check they're the same.
3. Needless to say, stick it all in source control if it's not already.
4. For your own sanity, run a code formatter over it if the code is messy.
5. I like PhpStorm as an IDE. It's not free, but the intellisense and refactoring support (and the built-in debugger) are timesavers.
6. Assuming it's not global variables everywhere, that they've used functions/classes(!), then as you fix bits of the code rename the single letter variables and add comments. PhpStorm can refactor variable names, so you see what will change before it happens.
8. Good luck! I like unpicking codebases like this and keeping them running. As a sibling commenter has said, it's an internal system so assuming staff are not going to exploit any vulnerabilities or you have guarded against those already, there is no problem keeping it running internally as-is. So long as you can still recreate the VM from scratch (I have had old packages disappear - now that makes for an interensting disaster recovery plan) and reinstall everything you need should backups fail, you're okay.
Correct, it's not free, but there is a 30 day trial. And... if you want to try it past that, it's $9/month on month-to-month pricing. For anyone working in "western" economies, it's near enough to free to at least give it a trial for a few months. The other 'big' competitors - vscode and probably... eclipse - both can provide value, but I've found the JetBrains stuff provide a much nicer out of the box experience for most PHP folks getting started out that that $89/year or $9/month to try is almost a no-brainer. But have also had people disagree, and almost always spend more than the $89 of their own time (or their company's time) getting VSCode set up with a collection of plugins.
Regarding mysql* i 'd guess it's probably easier to just replace it with mysqli_* calls. Only a few changes would be needed unless the app is doing something unconventional.
Getting a copy of PHPStorm will make things much easier, you can run Reformat code on PHP files and you can also do mass updates from code inspections.
Also worth checking out is a package called Rector (https://github.com/rectorphp/rector) which will automate a lot of this by scanning the codebase and providing diffs so you can upgrade safely.
> Is there a way for me to have an IDE with a kind of "compiler" that would help me convert this to PHP 8 so I can migrate it on a more recent VM? Of course there's 0 budget for this.
There is your problem. If it's runs on PHP5 (<?php phpinfo(); // in a php page), it might run without hurdle on more recent versions of PHP... or not, but PHP8 isn't a different language, they just added some stuff on top of PHP5. C extensions might break though, because yes, PHP relies heavily on them as the language is too slow to do anything meaningful like writing a database driver.
> PHP8 isn't a different language, they just added some stuff on top of PHP5.
there were some backwards-incompatible syntax changes between PHP 5 and 7 though. a client once switched on PHP 7 on his ancient WP website and it stopped working altogether because it used some weird no-longer-supported form of `new Foo`.
IDE: Visual Studio Code with the PHP extensions, free.
Compiler: you are looking in the wrong direction, PHP is interpreted. There were some compilers, but it's not what you need.
Converting to PPHP 8: do you need that? what are you trying to achieve? You can keep the app another year or so it it is working, don't fix what is not broken. There is no way to convert to 8, you need to rewrite it, PHP become more object oriented with each version and that is a paradigm shift there is no converter for.
I was able to convert a PHP 5.4 app to 7.1 but after that there are too many backwards incompatible changes to be easy to fix. Even the upgrade to 7.1 took a few days of tweaks to the code.
In my case the upgrade was demanded by security because the latest PHP5 release is no longer maintained.
For an internal app you're much better off just leaving it on PHP 5. Maybe add an op-cache for performance.
I know PHP is interpreted hence my comment "to have an IDE with a kind of "compiler"".
What I would like is an IDE experience: everything that isn't PHP8 compliant is underlined in red so I can fix the thing without launching the app every time and see if I broke something.
I maintain half a dozen PHP apps written for PHP 4-5, all of which now run on at least PHP 5.6, and a few of which I've gotten to PHP 7. Advice given by everyone else is excellent. PHPStorm is a must for me, one of the only pieces of software I pay for instead of using some OSS alternative.
One thing on automated tools: getting a good result is decently tied in to the structure of your project in my experience. A common scenario I've seen is projects relying on requiring other files as part of their business logic (IE, parent file A includes file B that processes and renders content vs file B including file A that defines helpers and what not). This is especially common when projects use something like index.php?file=whatever for URLs. Most automated tools and IDEs will struggle with this and false-flag undefined variables, etc, because there is no hard include path. There are a lot of ways to resolve this but it depends on your project.
Also, PHP 7 is much more aggressive about warnings on types and various other things. Unless you adjust your error reporting settings, you'll likely see a ton of these when you finally switch. I personally enable them on dev so I can clean them up, and keep them reporting to Rollbar on production.
As others pointed, the best thing you can do is learn to debug PHP interactively with an IDE (easier locally) so you can step, REPL and so on, into a mess of a code to improve it
I don't really understand why in 2020 there's still this kind of blind hatred against this language. It often comes from horrible bad memories from previous versions or old frameworks.
Objectively, compared to other languages i've been working with it is more than OK. Despite it's lack of "style" it is easy to understand, host, tests, diagnose and it is powerfull for web applications.
I've been working on a SaaS API with Symfony now for 2 years, our metrics are good...
It is a good tool, it builds good softwares
It's essentially sinking in popularity because of bad faith and lack of hype, really sad !
> I don't really understand why in 2020 there's still this kind of blind hatred against this language.
Well, the language is burned for a whole generation of devs, and it's hard to lose the nasty stench once it has settled.
A major reason might be that you don't touch again what you learned to dislike. Because you known anyway that it will be painful, why go for it?
> It often comes from horrible bad memories from previous versions or old frameworks.
Those old versions and frameworks are still around. Companies don't lose their legacy fast.
> Objectively, compared to other languages i've been working with it is more than OK. Despite it's lack of "style" it is easy to understand, host, tests, diagnose and it is powerfull for web applications.
That always was the case with PHP. Doesn't say whether it has lost it's old flaws.
> It's essentially sinking in popularity because of bad faith and lack of hype, really sad !
Is more losing because of competition. PHP still is mainly a web-stack backend-language that can't offer much in other areas. But now there are other languages who can equally shine on backend, while also shine on other areas. So obvisouly people go for the language which can give them more, instead of less.
I haven't found any good arguments against PHP in the comments here, just pure hate.
Let's name a few of the arguments people are making:
1. Its variables start with $ and that is ugly: I mean, come on, I won't even entertain this bigotry.
2. It used to be better before: This is just pure nonesense, before OOP PHP wasn't good to create any big and well-structured application, it is ironic because most of the bad opinions about PHP come from people who used it a long time ago. Besides, you can still use PHP as you used to, but now you have more tools at your dispossal, You are free to use it as before.
3. It is trying to be Java: Well, sure it is more like Java, only less verbose and easier to write. Developers can be much more productive in PHP. And moving in the direction of Java is not a bad thing as the language moved into the Enterprise space. I worked with Magento every day and I am glad the language is more than Java than it used to be, it means we can organise our code better. Again, ironic that some people who mentioned this as something bad about PHP, then went on to say they prefer Java.
4. Composer has made the language worse: Honestly this is so ridiculous... so now having package managers is a bad thing? I haven't met an actual professional PHP programmer who holds that opinion. All of them like composer, it makes reusing code and creating apps in PHP much easier.
At the very least it seems nonsensical and cargo-cultish: As a non PHP-er, what is the actual purpose of $? In Perl, it indicates variable context (for better or worse, there's more than one, so it has to be indicated somehow). In shell, it indicates the substitution of variable name by its value. In PHP...I draw a blank. It really seems like an "I wanted my language to look like some other language but I had no idea what it should be doing" kind of thing.
but because early PHP was more simplistic than Perl it only has $.
Powershell also uses $ for variables.
Regardless of etymology of the $ sign and the usefulness of it, personally I like it because it makes it easier for me when I'm reading code, especially if you are scanning fast, to differentiate variables from symbols. Yes, you can get that with your editor too, but for me it is easier to associate the $ sign with a variable rather than a specific color, sometimes you don't have coloring available like when in command line going thru diffs, cat, nano etc.
It seemed kind of obvious to me even at that time that it was taken from Perl. I just didn't get why. PHP could have lifted IMPLEMENTATION DIVISION from COBOL, but likewise, there would have been no point either (fortunately it didn't do that!).
Early web was written in Perl, I guess it was the classic approach of lets borrow what is already successful and in end PHP won over Perl so it worked too. Bill Gates would have been proud.
It differentiates variables from global constant things (constants, class names, function names, ...) for which the scoping is different. So you can have $strlen = strlen(...);
Off the top of my head, I struggle to come up with situations where you'd need an $ to distinguish class names or function names syntactically. Hell, in Lisp I can do (let ((length (length seq-1))) ... (length seq-2) ... ) just fine and it still works as expected, so no special characters necessary either.
Plus, to have different scoping rules was considered a good idea? Weird scoping issues were why I gave up on Ruby fifteen years ago; perhaps it was a good idea that I got never that far with PHP. But I'm intrigued now; what exactly are the scoping differences in question?
TBH, I don't know lisp and I have no clue what you just wrote. Someone new to PHP can just be told $something is how variables look like. And they will recognize variables forever from then on. What's a variable in that lisp code, or in any general lisp code? I have no clue at first glance.
I didn't say it's necessary for the parser, but it's useful for the learner/user.
It means the start of a variable name, as simple as that, it isn't anything significant. Maybe it was made to make parsing the language easier at the time, who cares?
You can get used to that in 10 min and move on with your life, it is not a reason to not pick up the language, it's bike shedding.
There was a number of other reasons why I didn't end up using PHP, so it was a bit like death by a thousand cuts. It was not the reason for me, just a small showcase of the weirdness for a newcomer.
> 3. It is trying to be Java: Well, sure it is more like Java, only less verbose and easier to write. Developers can be much more productive in PHP.
I suppose if you are equating extra keystrokes to productivity, then sure. However, Java has vast ecosystems and standard libraries that dwarf most languages. The real gains in productivity are in not re-inventing the wheel for everything. Verbosity has little to do with productivity in the bigger picture.
You are proving my point by defending Java against PHP because my argument was that being more like Java isn't a negative thing.
The productivity point was a secondary point but when it comes to building websites I think people can build faster in PHP although I guess that depends on many factors.
I guess I am not following your argument. Are you not saying that since PHP is less verbose than Java, this is better for productivity? After which you then follow up and say that PHP becoming more like Java is not bad? Seems contradictory, no?
My point was that it was ironic for people to say that PHP becoming more Java-like was a bad thing, but then they said that they prefer Java to PHP.
You are right, I did sneak in there that I find PHP less verbose than Java as an advantage, since most people complain about how much typing you need to do in Java I thought this was worth highlighting.
However personally I think PHP evolving to be more similar to Java was a good thing, even better because imo they copied the good parts, ie: OOP instead of the verbosity but that's up for debate.
In short, becoming more like Java was good, but PHP isn't Java and has its own advantages for web development, imo this is that it is less verbose and easier to write.
I have my reasons to _despise_ hosting PHP from an operational perspective. These mostly come from having to host ready-made PHP applications like Nextcloud, Wordpress, Dokuwiki, etc.
1) 'Language configuration' kept in a php.ini that is usually not shipped with any project. Instead, each project tells you what flags to flip so that it runs, but very often every distribution ships PHP with slightly different flags, effectively making it _very_ hard to have a 100% correct php.ini.
2) 'Deployment configuration' that is additionally present in your FPM/apache configuaration. Again, you have to be told by a project that that these given options (often related to timeouts and request size) have to be set. Many projects just assume you have some 'sane defaults' like things bumped up from the defaults. Again, very difficult to get reproducible deployments of an app, unless the developers are very insistent on documenting everything.
3) Extremely painful to debug. If 1) or 2) are broken and a connection terminates during an upload with some 400 error, the error can be in multiple places: nginx/apache, php-fpm, or the PHP code itself. Each one of them logs to a different place, or not at all. It's difficult to actually understand the _source_ of the error. Good luck. Bring strace.
4) Broken upload model. If I understand correctly, all file uploads in PHP must end up on the local filesystem, and they are impossible to directly stream onto something like S3. This means that my Nextcloud instance will first save a few gigs of data on /tmp, and then only punt it over to S3. Gross.
5) Annoying to host in containerized environments. Both Apache and nginx are the kind of applications that insist on doing a bunch of setuid()s, thereby breaking on hardened containerized environments. Not to mention having to host a nginx+fpm/apache combo per application just seems wasteful, but there's no other easy way to deploy PHP apps in a containerized way that I'm aware of.
6) Configuration woes with rewrites, static files, etc. This is related to 2), in which you have to spend a bunch of time configuring your HTTP server in order to split up requests between static file serving and PHP, set up rewrites, and hope you don't accidentally introduce a security vulnerability.
All in all, compares to something like 'here's a go binary, run it, push HTTP traffic to it, it will serve its own static files, too', PHP is an _extreme_ pain in the ass to host.
You're not being fair to the argument #3. PHP is becoming a less good Java. That's the problem. It's like Java, except it doesn't have generics, doesn't have real data structures (List, HashMap, Deque), no threads or async, no method/function reference or typed function parameters, etc.
So the whole "It's trying to be Java" is more like "What does it offer that's better than Java? Because Java has stuff that is better than PHP."
And I'm saying this as someone who doesn't like Java at all.
It doesn't need them IMO. It brings no benefit to the language, really. They would need to be type checked at runtime, which can become quite expensive. Static analysis is a better option for an interpreted language. Read this answer from Nikita (one of the top PHP contributors) https://www.reddit.com/r/PHP/comments/j65968/ama_with_the_ph...
> doesn't have real data structures
Untrue. See https://www.php.net/manual/en/book.spl.php It's usefulness is limited though, because it's rare that you need those types of data structures for web applications.
> no threads or async
Untrue. All kinds of projects like Swoole (gives you a runtime similar to Go) and ReactPHP (runtime similar to Node) and https://github.com/krakjoe/parallel for lower level concurrency. There's also pthreads https://www.php.net/manual/en/book.pthreads.php But again most of these aren't necessary for most apps because of PHP's request-response model. Useful for one-off services though.
> It doesn't need them IMO. It brings no benefit to the language, really. They would need to be type checked at runtime, which can become quite expensive. Static analysis is a better option for an interpreted language. Read this answer from Nikita (one of the top PHP contributors) https://www.reddit.com/r/PHP/comments/j65968/ama_with_the_ph...
Right. You need to use something like Psalm if you want the benefits of generics, which is basically a tacked on type system. Having static checking is absolutely beneficial. I'd be willing to bet good money that you don't write PHP without typehints and/or Psalm/PHPstan.
> Untrue. See https://www.php.net/manual/en/book.spl.php It's usefulness is limited though, because it's rare that you need those types of data structures for web applications.
You're totally right. I was thinking that you still needed to explicitly enable SPL, but that hasn't been true for a long time, IIRC. So, fair enough. I was wrong here.
> Untrue. All kinds of projects like Swoole (gives you a runtime similar to Go) and ReactPHP (runtime similar to Node) and https://github.com/krakjoe/parallel for lower level concurrency. There's also pthreads https://www.php.net/manual/en/book.pthreads.php But again most of these aren't necessary for most apps because of PHP's request-response model. Useful for one-off services though.
pthreads was never worth much. It never worked on web servers and is now deprecated. Parallel is a PECL extension, which may or may not be considered part of PHP, IMO. I believe it also doesn't use threads unless you use pthreads (which you should/can not). So it's just multiple processes- not threads or async. I don't know much about Swoole, etc, but those are frameworks- not PHP itself. Also, I believe Swoole is process based, not thread or (true) async. I could be mistaken. So, again, AFAIK, PHP does not have threads or async.
That's not what I meant. My wording was poor. I meant specifically `callable`. You can't typehint the inputs and outputs of `callable` parameters. So passing around lambdas, etc, is not robust/safe.
> You do those like this: [Example::class, 'someFunction']
Yeah... an array of two strings. Again, I should've been more clear. I know that's how you refer to functions in PHP. But it's not the same as actually getting to write Example::someFunction and knowing that the inputs/outputs line up with whatever you're doing. If you're lucky, your PHPStorm or whatever can tell where you're trying to refer to a function and maybe point to it for you, but otherwise, it just thinks you're passing some strings around, because you are.
> I'd be willing to bet good money that you don't write PHP without typehints and/or Psalm/PHPstan.
Yeah, think of it like Typescript. Same idea.
> Also, I believe Swoole is process based, not thread or (true) async.
It's a coroutine model, like Go. Very fast. But I don't use it because it's primarily a chinese community, lots of the docs are in broken english. But it's an impressive thing anyways.
IMO, you don't need threading in PHP, there's not really that many situations where it would help during a request-response flow. People generally delegate slow tasks to job queues, which often use https://www.php.net/manual/en/function.pcntl-fork.php to fork off workers. Works great.
> That's not what I meant. My wording was poor. I meant specifically `callable`. You can't typehint the inputs and outputs of `callable` parameters. So passing around lambdas, etc, is not robust/safe.
You can though. `fn(SomeClass $foo) => $foo->doThing()`
> and knowing that the inputs/outputs line up with whatever you're doing
Fair enough, but you can use reflection to look at the callable if you care enough. It rarely matters.
> It is trying to be Java: Well, sure it is more like Java, only less verbose and easier to write. Developers can be much more productive in PHP
This sounds like kool-aid. Any productivity gain from reduced verbosity would be minimal. Typing out two extra keywords for your method signature is not going to affect your productivity in any real way in reality.
And it being dynamic. If just want to dump some JSON or a CSV into an array to do something with it it is probably going to be much quicker than in Java.
The latest version of PHP that I used was 5.3. The power, and disadvantage, was that it was basically a scripting language which allowed for quick prototyping and easily making some of a site dynamic and allowing for templating. For the more serious/involved/enterprise applications, a lot of workarounds were needed to cache database connections etc.
Lots has improved: ide support, jit, package manager. In doing so it became more mature now joining the realm of more serious, enterprise, languages which had all of this for ages. As such it is also being compared against those languages. At the same time templating is now easier and more cheaply done through static site generators. So imho PHP falls a bit in the middle and it is only kept afloat because of the likes of Magento, Wordpress, and other big products built on top of PHP that thrive by being modifiable by practically any developer.
> I worked with Magento every day and I am glad the language is more than Java than it used to be, it means we can organise our code better
Do you consider Magento being a framework you are happy to work with? I'm also working in Magento 2 and honestly it's a painful experience. It's a so bloated framework that without cache enabled the development is completely awful.
There is a discrepancy between what’s hip, and what’s actually used. On places like HN where everyone is in love with Ruby... errr... Go.... errrr I mean, Rust, you’d think that those languages are the what’s what.
Then when you look at the job market, you get a very different picture of what actually gets used. In my country there hasn’t been a single job posting for all Rust in all of 2020. There’s been a single mention of Go as a “nice to know” PHD job at Google Denmark and there is just a single company who has had openings for Ruby. Hell even with everyone’s favourite Python, almost every job involving it is in DataScience and needs you to be a mathematician first, analyst of some kind second and a programmer third. There are a few django jobs, and good for those guys, but in general, even python doesn’t see that much general usage.
The vast overwhelming amount of jobs that’s been listed in 2020 in Denmark have been for C#, PHP and JavaScript, with JAVA still hanging in there somewhat, though typically bundled with whatever they call JBOSS these days.
So unless you’re smack in the centre of Silicon Valley, I probably wouldn’t worry too much about the hate PHP gets.
> One of two PHP major web frameworks borrowed everything they could from it.
Weird flex.
So you're saying that an aged veteran in any sport who observes and learns from his younger peers should be looked down upon as being on their bandwagon? Their growth, improvement and continued success should be discounted?
This is because you‘ve built up expertise and know the ins and outs of the language and frameworks (which are often very complex and idiosyncratic to achieve their cleanliness and expressivity). You know what to use, how to use it, what to avoid, how to debug stuff etc.
However for people who have not invested this time and effort it is an objectively worse language than other web focused ones in many dimensions.
PHP is a workhorse for the web and still the most important language next to JS in that regard. But there is a reason it is declining (slowly) as well.
I think that's it. No argument that it's improved, so much, but if you're not already using it then it's hard to pick it over other options. Good luck to the fans though, you can do anything you need with it and if you enjoy it all the better.
That's correct. It turns out that it's also bad, though. People don't like to hear it because I'm "just a hater", and maybe one or two of these issues isn't a deal breaker. And yes, you can write real, useful, applications in PHP, but it's a terribly awkward language with a lot of missing features and sloppy dynamic typing nonsense.
* No (real) async or threads (pthreads never worked on backend and is deprecated anyway for those who always mention it in response to me)
* No generics
* Interfaces must be complied to at class definition
(leading to verbose nonsense like the "adapter pattern")
* No const or immutability
* `array` is a shitty hybrid of an actual array and a dictionary and it sucks at both
* No other native data structures beside the shitty `array` mentioned above
* No ability to typehint callable function params
* switch statements use loose equality checks, so you should avoid them
* foreach is broken and leaves a dangling reference
* `array` keys are automatically cast to int if they can be, which is broken and insane. (E.g., if I use `array` as a dictionary and one of the keys is the string "123", it will NOT store the entry as key-value pair: "123" -> $data. It will instead store $data in the 123rd slot of the "array". Iterating this `array` with an index will end in a bad way).
But surely someone will drive by and say that none of these things matter and that an experience PHP dev would never be bothered by any of these things, etc, etc. "You can write bad code in any language."
But... you can always just choose a better language if you have the choice. I feel like people get Stockholm syndrome over their tech choices. It all sucks, but some suck worse than others. Don't tie your identity to shitty stuff like programming languages: "I'm a PHP dev." "I'm a Rust dev." Give me a break.
People keep saying “PHP in ${current_year} is actually great, it only sucked in ${current_year-5}!” - I feel like it still sucks[1] today, but it’ll take 5 more years for the fans to realise it, when they have the PHP from ${current_year+5} to compare against :P
[1] Being slightly hyperbolic - I won’t deny that you can do good things with PHP, as you can do good things with any tool; and AFAIK it’s still unmatched when it comes to low barrier of entry and shallow learning curve.
(I’m coming from the perspective of someone who mostly uses rust, python, and PHP7.3, with odd bits of Hack - in the past week, PHP7.3 has frustrated me with lack of typed arrays, lack of typed properties [fixed in 7.4! Only took 5 years between the introduction of type declarations and consistent support for type declarations...], and dictionary keys being automatically cast from string to int if they look vaguely numeric. It’s a shame Hack never took off in the open source world, as it’s basically “What if we could reimagine PHP without the legacy baggage?”)
The key to becoming a person who thinks PHP is great now is to primarily use features that have existed for more than 5 years. For me, PHP 7 was PHP 5 that was faster and had some nice little bits of new syntax. They started down the type system road but I avoided it then.
Now it seems like the basic type system is in place, great. This new stuff in the article I'll probably start using it when 8.4 drops.
5 years is an exaggeration, but staying a version or two behind really helps you stay sane.
By the way I found Hack/HHVM thoroughly disappointing. Tried running some fairly complex apps on it and it felt like they reimagined the legacy baggage. Seems like PHP itself borrowed a lot of ideas from it though.
Probably the package/ framework ecosystem. There is also a self reinforcing quality, there are a lot of devs which in turn encourage people to do projects in PHP to access those devs.
It depends on your goal. I personally think PHP still wins for a solo developers in speed of feature creation. Think of the ratio of business value per development cost. Someone should find a way to objectively measure this.
Same here. Sure, PHP in 2020 is a mostly passable language. But then next to it you have Java/Kotlin/Scala, Go, Clojure, Node w/ TypeScript, even Elixir is pretty awesome.
Though, to be honest, I'd probably use PHP over Node even with TypeScript because the Node ecosystem is such garbage.
You just have to really like Laravel, I guess, to choose PHP in 2020. Which is totally fair. I haven't used Laravel, but people do rave about it.
More than anything, I find the language $ugly. Is that fair? No. Am I being unreasonable. Yes. Do I love PHP? Gross. I just have to live with it and go past the ugly syntax. It’s like an unhappy marriage. It’s just fine.
I think PHP is a fine language if you are working on an existing application or are building on top of symfony but I’ll begin second guessing all your design decisions if you increase the default execution time of php from thirty seconds to over five minutes. I submit PHP does not belong anywhere outside the request response cycle. If you use it for other stuff, you are not wrong. I mean I’ve used puppeteer and node js to capture screenshots and I still think that ideally JavaScript should only exist in client-side web browser based development. I would never voluntarily do any of the react native or express/hapi server side development with JavaScript. I will do it if there is money involved, it just isn’t my preference.
It is ok to have a preference to do non web work with PHP but you owe it to yourself to at least try something else before saying you prefer it over everything else.
There is nothing wrong with $ though. That’s just insane. Also I’m very excited to see Drupal 9 being released with twig 2 support and more recent symfony support. I just think you should at least evaluate other options before saying “everything goes better with php sauce” just like the JavaScript crowd should stop and get some help before using JavaScript for native development and or server side development.
Maybe think of money everytime you see the $ symbol, to make it more palatable? :P
On a serious note, I find the JS ecosystem more annoying than PHP. Modern frameworks like Laravel (Laravel is nice to work with), PHP is more than enough for its intended use - web applications. PHP 7 has good performance improvements too.
The funny part is that all the hate they have towards PHP, pretty much most languages have similar or other problems. I say this as someone who loves languages like Go, Python but I run a SAAS business in PHP which brings in close to 7 figures ARR and employs 15+ people. All these developers shitting on PHP are basically the elitist form of "I don't do PHP so you shouldn't either because it sucks and <my shiny language> is so much better".
I know people who run decently sized and successful businesses in a variety of mind-numbing technology (try FileMaker scripting or shell scripting) but that definitely doesn't mean those things don't often suck and that there aren't advances in PL's that don't or won't lead to better software. (I personally don't use PHP at all because I haven't yet seen a reason to use it for any new projects over Python or TS. Is that new match expression proper pattern matching? ;))
It's pretty hard to draw a link between these things and commercial success, but it somewhat unseriously reminds me of Jonathan Blow's warnings that eventually everything is just going to fall apart.
Yes I am not necessarily disagreeing. I am saying that people who shit on PHP think that other languages are somehow this magic wand that is so much better. I challenge the "so much better" part because the cost vs benefit matters.
Because those of us who know and have used several languages tend to develop a preference for expressiveness, terseness, safety, and dare I say, elegance.
PHP (and JavaScript) gained and maintain their relevance, despite being inferior languages, because of their historical placement. I'm sure COBOL has improved over the years, and we know it is still used and "needed"... because of its historical placement. But you probably wouldn't use it, either, unless you had to (or you didn't know a better alternative).
> It often comes from horrible bad memories from previous versions or old frameworks.
Not only that. There is a huge amount of devs hating PHP w/o ever having worked with it. Same with Perl.
Few months ago I was debating with a friend working since 15 years on PHP, my point was php is slow and max throughput is 200-500 rps, which is quite low compared to Go, node.js, C# and others, he answered that 100-200 request per second is more than enough for most use cases.
I'm working on systems with 25K RPS at peaks, but for simple projects and small companies he is right ... But why should anyone start a new project in php now that we have so many good alternatives?
"he answered that 100-200 request per second is more than enough for most use cases"
Exactly this. If you already know PHP and can produce results (mostly CRUD apps) and it doesn't need millions of rps, why do we need to use another language because they are so much better ? So much better at what ? It is like saying "I have a hammer, so everything looks like a nail to me". Not every web app has to be written in Lua/Rust/Go/Julia etc. Each language comes at a cost. No free lunch.
"But why should anyone start a new project in php now that we have so many good alternatives?"
Because everything comes at a cost. You want to use Rust instead of PHP ? Sure, sounds great. Now lets go find a really good Rust developer who also understands how to host it correctly and then if he leaves, can I easily find another Rust developer ? Hmmm. You also need to account for maturity, ecosytem, hosting, maintenance etc which are all real world problems. Building a new shiny toy project ? Go ahead use whatever language you love. Again, it is about cost vs benefit.
I can’t even say what’s wrong with PHP, because— okay. Imagine you have uh, a toolbox. A set of tools. Looks okay, standard stuff in there.
You pull out a screwdriver, and you see it’s one of those weird tri-headed things. Okay, well, that’s not very useful to you, but you guess it comes in handy sometimes.
You pull out the hammer, but to your dismay, it has the claw part on both sides. Still serviceable though, I mean, you can hit nails with the middle of the head holding it sideways.
You pull out the pliers, but they don’t have those serrated surfaces; it’s flat and smooth. That’s less useful, but it still turns bolts well enough, so whatever.
And on you go. Everything in the box is kind of weird and quirky, but maybe not enough to make it completely worthless. And there’s no clear problem with the set as a whole; it still has all the tools.
Now imagine you meet millions of carpenters using this toolbox who tell you “well hey what’s the problem with these tools? They’re all I’ve ever used and they work fine!” And the carpenters show you the houses they’ve built, where every room is a pentagon and the roof is upside-down. And you knock on the front door and it just collapses inwards and they all yell at you for breaking their door.
That's funny and all, but it doesn't drive home much more of a point than "PHP is bad because PHP is bad". The insinuation that all "houses" built with PHP are defective and waiting to fall apart is so obviously untrue that it feels unworthy of discussion.
A more reasonable analogy would be that there's a standardized toolbox that carpenters use that's weird, quirky and sometimes so bad that you need to know workarounds to use it correctly, but the houses that are being built do what they're supposed to in the vast majority of cases because most of the carpenters know the quirks well.
The question then is, if you're contracting someone to build your house, or you're the manager of a construction company, do you go with the standard toolbox that's used by the X% majority of carpenters, or do you hire carpenters that use more obscure (but functionally "better") toolboxes while running the risk of now ending up with unmaintainable or deviating houses that are hard to recruit additional carpenters for because they refuse to work on what is quite objectively "non-standard" houses?
The answer in my mind is no less complex than it would be for software development: it depends, and you should be wary of anyone telling you that it's "obvious" that the answer is one or the other.
I think a better analogy would be that the PHP carpenters have standard old tools that people have used forever, and they work just fine. Normal hammer with wooden handles, normal planes, etc etc.
But there are modern carpenters that have hammers that are 100% metal and never break and actually improve your hammering power. The new electric hand planes work a lot faster, though you do have to be more careful because they can get out of hand quicker. etc etc.
In the end, they both build houses. The old-school carpenters might take longer, and they might have to know more techniques, but they get there in the end.
On the other hand, the modern carpenters sometimes go a littler overboard with their tools and have problems that old-school carpenters don't have, especially with their tools randomly stopping working in the middle of a job. It might not be often, but it happens.
To add to that, the old-school carpenters can actually use a lot of the new tools, too. They fit into the workflow and can be adapted to their old tools. It's just that they primarily stick with their old tools because they're used to them.
It's kind of interesting how much the world of woodworking and software development overlaps in that way.
> On the other hand, the modern carpenters sometimes go a littler overboard with their tools and have problems that old-school carpenters don't have, especially with their tools randomly stopping working in the middle of a job. It might not be often, but it happens.
Great extra point. I'm often surprised at how much random breakage other people just accept as normal in "modern" webdev (meaning, for better or worse, you're involving javascript somewhere in the process). Put another way, I'm frustrated by how much I'm expected to just 'deal with' because a seeming large number of other people don't see a problem with it (or don't see enough of a problem with it).
Your analogy makes is sound as if the problem with PHP is that it's old or lacking features, whereas the point of the original analogy is that it's poorly designed. (Python is older than PHP, so it's not a question of being modern or not.)
Many good and well-designed languages are older than PHP (Scheme is from 1975!), so that cannot be the cause of PHP's poor design.
Rasmus Lerdoff actually gave a great talk on why he created PHP and how it sort of accidentally turned into a programming language:
https://www.youtube.com/watch?v=nmD1Q4FsXCc
I don't want to get into an "all languages are the same / all languages have quirks" kind of thing, but the idea that PHP is weird, different, and in a sense inscrutable, and this has an impact on its use and performance, just doesn't bear out.
Yes, it has quirks -- so does C, so does C#, so does JS, so does lua, so does tcl, so does every assembly language I've ever worked with.
So what? Are those preventing people from writing good code? Are those preventing people from shipping? Could it be improved? Has it already been improved? No, no, yes, and yes.
The biggest reason PHP's gotten so much scrutiny, to where people write these kinds of posts, is its ubiquity. When JS moved from being that simple, silly language built into the browser into a widely used one, we started seeing slide deck gags about the inscrutability of its comparison operators, yet JS seldom attracts this level of derision.
You can't rely on a compiled/JIT language to address performance requirements. There's always time when your server is overloaded, no matter if it can handle 100 or 10000 RPS. You should architect your app with scalability in mind. And then there's not much difference between languages, only marginal savings on infrastructure. But one month of decend web server host costs about the same as one hour of decent software engineer.
I am wondering this: are people who do crud apps (in php or otherwise) do consider race-conditions in the database? Like one query and then based on that query another one which inserts/updates? And if so, where can I read about the standard techniques used in practice?
Thanks. So is the general industry practice? I read MySql only supports this since like 2004, somehow reading material doesnt seem to be too concerned about these.
well, on the other hand, if you are starting from scratch as a new developer, trying out go or rust is not too risky as large orgs backing it up. Also, for me, hosting go is much easier than php, as I am not from that era.
I don't believe the constraint would be the language itself, not with accellerators, opcode caches, JIT compilers, etc. I've always been told that PHP's performance is more down to the database than anything else.
I don't know where you pulled that number out of, but I just used an outdated version of `ab` to request the Hello World page of a fairly heavy PHP framework on a modest virtual server and got over 4k rps. Give me a proper server box and a well-written application, and I'll deliver the 25k rps that you want.
Besides, most webapps spend most of their execution time waiting for the database, memcached, redis, elasticsearch, or whatever. The speed of the language runtime makes very little difference.
Because the alternatives is actually not good, it just a fallacy.
There will always be something negative regardless of what you pick, problem is to decide what your core values are when writing different types of software. If you don't, you are just comparing apples to oranges.
When it comes to PHP, core values are usually things that has to do with tooling, server architecture & deployment, not much the language (syntax, expressions, lambdas, classes etc) it self, except maybe it is easy to learn & use.
This means that developers who comes from a background of that the language itself is the most important part of a project will most of the time just get confused what PHP is about.
This is correct only if you run "Hello World" apps on a single server. PHP scales horizontally so any real-world application can easily scale to 10, 100 or 1000 servers. If there is no other scaling challenges (like databases) then it can scale forever thanks to its beneficial process model.
Well, good performance of http request/response cycle is mostly related to async operation, in some form, when long-lived daemon can process big amount of requests without spending time on initialization. Workerman and swoole, powered by async PHP approach, are very fast and suitable for high load. The problem with async PHP, though, is that you need to be careful with libraries (e.g. mysql client) because most of them were designed with short-lived PHP script execution in mind.
"A long-standing goal of the WordPress project is to be compatible with new versions of PHP on their release day. The next major version of PHP (version 8.0) is currently scheduled for release on November 26, 2020. WordPress Core contributors are working to ensure PHP 8.0 is supported in the next major version of WordPress (version 5.6), which is currently scheduled to be released on December 8, 2020."
Possibly not what the author meant. Support for PHP 8 in WordPress will come soon after PHP 8 is released. But to upgrade WordPress to PHP 8, that is to rewrite its codebase to make use of PHP 8 features, probably will not happen anytime soon. WordPress still has a minimum PHP version requirement of 5.6, so...
Drupal 5/6/7/8 intentionally broke backward compatibility between versions in order to move the architecture and the feature set forward. The net result is that they are now at a point where Drupal could drop PHP 5 support. They also moved towards modern PHP / coding practices over the past years (Not invented here -> Proudly found elsewhere, composer, PSR's, OOP,...).
WordPress stuck with preserving backward compatibility and so the core API's have never seen a fundamental breaking change between versions. New features have been tacked onto what was already there over time.
I have kept a personal WordPress blog since 2005 and I have always been able to easily update things without migration pains. Of course, I run a minimum of customized code (beyond a custom theme that is). And I suppose YMMV and you still might have a different experience, if you did heavy customization through plugins, heavily leaning on WP's core API's.
Drupal? Totally different experience. Breaking changes and fundamental alterations of the database schema have been par for the course. I've seen 6 month long migration projects to migrate crucial enterprise data between versions. The PTSD of migrating from Drupal 6 to 7 to 8 is real.
Then again, WordPress and Drupal are different tools despite a significant use case overlap. I'd be weary to use either Drupal for a simple blog, or WordPress for an intricate, tailored back office application. I think they are both designed to do different things all together.
Having said that, it's worth noting that the Drupal project is very aware of past pains. One of the big goals of the past few years was working towards avoiding big breaking changes between major versions. It is purported that migrating between Drupal 8 and 9 is far less painful. Of course, it remains to be seen how that holds up in the long term.
I'm not sure why you're asking or what new features you'd like them to take advantage of, but given PHP's reasonable approach to backwards compatibility, I expect that it won't take too much effort to get Wordpress running on PHP 8, but obviously it's not going to utilize much of the new stuff that way.
A lot of those changes look like good things taken from other languages that have done it well (the null ?-> and ??, ...).
But many things seem to be quite of a burden instead of a progress => why create a new match syntax when a switch is already well known for something similar? That will create confusion (thinking of all the for types of loops in JS!), plus it's still not an enum and cases will be missed.
And the worst being the attribute #[] syntax... why?! Almost every other language uses @attribute, and it is successful: simple to write, easy to read, why on earth a new and such complicated solution?
While php is making progress step by step, it has no chance of ever becoming of good reputation if it goes all the way to make itself more crazy.
> And the worst being the attribute #[] syntax... why?! Almost every other language uses @attribute, and it is successful: simple to write, easy to read, why on earth a new and such complicated solution?
Simple, it was already taken up [1]. Also `@attribute` syntax is by no way universal (and semantics wildly vary even with the same syntax): `#[]` in particular might have been inspired by Rust.
The rfcs have a lot of discussion on those subjects indeed, but I still disagree with the choice!
Also, the current use of @ is before a function call or some get, not before a method/class/... declaration, so a change in that direction would probably be possible. (plus the @ to suppress errors should probably be removed from the language anyway!)
> And the worst being the attribute #[] syntax... why?!
Hah. Since the initial RFC was agreed, I think there were three changes to the syntax because no-one could agree. At one point it was going to be `@@attribute`. #[] is similar to or the same as Rust, I believe. It also has the advantage of being backwards compatible; while rarely used, comments in PHP can start with # instead of //, so older versions of PHP will just see an attribute as a comment. Of course, that also means that a comment in old code might now be interpreted as an attribute, but there you go.
Single @ is probably a no go because @ is already the error suppressing operator. Now, in my opinion that should be ejected from the language with extreme prejudice, but I doubt it ever will be.
PHP laughably adds warts almost as fast as it removes them, then codifies the new ones as intentional. Hack was a good attempt, but I fear it's too late to fix the soup of features by forking/cloning. I sincerely believe another language will replace it (not python), if they havent already (javascript shudder).
I've used PHP professionally for over 20 years along with other languages. The decisioning of language design, at large, has been mired in "good enough and doesn't break backward compatibility" nonsense all over the spectrum. PHP was the poster child of thinking differently in the 90s. Make the languages BETTER by looking at others, not clutching your Perls /s. Arcane sigils are not the way forward, that's a known (eg Erlang, Haskell, Pony, Perl, etc), even with powerful features that put existing languages to shame.
I'm not up to date on php code, but can't the first example be done using reflection? For example a SubscriberBase class which: lists all of its "on*" methods, checks if there's only one parameter, gets its type via https://www.php.net/manual/en/reflectionparameter.gettype.ph... and registers the method to receive events of that type.
From the docs it looks like it's possible in php7 and doesn't need explicit text mapping. But maybe I'm missing something?
I'd need to check if this is still the case in PHP, but Reflection was orders of magnitude slower just a few short years go for cases such as ReflectionClass->methodExists() vs method_exists()
PHP picks up ideas and syntax from many other languages. I'm happy about it, because it popularizes and normalizes concepts that used to be niche or advanced.
C established a lot of common syntax, and there's some consensus for post-C syntax emerging, like `name: type` syntax, `match` expressions, non-nullable types and operators for them.
Nowadays `[1,2,3]` seems like an obvious syntax for array literals, but it wasn't obvious before JSON and other languages converging on it.
I know you're trolling, but FYI the `static` before function has nothing to do with the `static` return type. Like other programming languages the term `static` is used to denote two things.
What would they use it for? The first 'static' means the method is a part of the class rather than the instances of that class. The second and third 'static' indicate late static binding, meaning they refer to the class being called, rather than the class defining this method.
(Disclaimer: I know absolutely no PHP whatsoever.)
> The second and third 'static' indicate late static binding, meaning they refer to the class being called, rather than the class defining this method.
Wait, so they're using "static" to mean the binding is happening later? Isn't that essentially less static than binding against the class being defined?
Well then I guess we'll have to agree to disagree :-)
It's less static than a method dependent on the object instance, but more static than a method that doesn't even depend on the class. If I've understood correctly (which I quite possibly haven't, in fairness), these are analogous to Python's static methods, class methods and regular methods, and its static methods really are the "most" static.
Please remember that PHP is more or less the only truly free (as freedom) community driven language suitable for both prototyping/pet projects and enterprise grade web software development. TypeScript and C# are Microsoft, Go is Google, Java is Oracle. Python is not suitable for complex multi-layered systems, Rust is too young and let's see where it will go without Mozilla. Ruby? IMO Ruby is in sunset phase, no new ambitious projects are started with Ruby.
Ruby is a fantastically good language with a slow bloated runtime. That killed Ruby.
Python was less good and less bloated, but still bloated.
I think we use Python now only because our computers are orders of magnitude more powerful than a decade ago when I was watching Python Zope slow to a crawl and die.
PHP has (almost) complete strong typing system and all the bells and whistles of OOP needed to implement said systems using proper patterns and methodologies and make it modular and testable enough to be robust and supportable for a long time.
Python has literally all of those things, and has been strongly (but dynamically) type from the very beginning. PHP is still weakly typed today. This code doesn't raise a warning or anything:
These examples are not about strong typing, but about type juggling. Strong typing is this:
declare(strict_types=1);
use \Domain\SomeItem;
use \Domain\SomeItemId;
use \Domain\SomeItemSpec;
abstract class SomeItemRepo {
public function GetOneByID(SomeItemId $id): SomeItem;
/*
* Still hacky
*
* @param []SomeItemSpec $specs
*
* @return []SomeItem
*/
public function GetManyBySpecs(array $specs): array;
}
That's an example of strong typing specific to PHP, then, and not used in the rest of computer science. What you're describing there is usually known as static typing, which Python also supports.
No, types are checked at runtime in PHP. You can also use static types with docblocks and use static analysis tools, and both play complement eachother.
Go isn't free? JS isn't free? Guile (which is probably as free as you can get) comes with a web framework too.
Also what does "enterprise grade" mean? I'm not sure if you're aware but the forum we're talking on right now is written in PG's lisp dialect. I'm pretty sure arc is free.
If we count C as a programming language with all it's nonsense we have to count JS. Your point with Go makes sense (although IMO it's better than most of google's "open source" projects.)
You didn't have an answer for Guile though. I'd pay money to be able to build web apps in scheme instead of PHP.
What does this even mean, only lazy ass projects are started with Ruby? Yes Ruby is declining in popularity, as does PHP. It doesn't mean these languages are dying, there's just way more options to choose from these days.
It is too loose typed and it's implementation of interfaces is too relaxed to use complex software engineering patterns and methodologies like DDD and SOLID.
It only has duck-typed interfaces, unable to verify methods' signatures. Trying to implement strong inheritance leads to monstrosities __instancecheck__ and __subclasscheck__ and manual type checking of injected dependencies.
Oh please don't get so flamewar-y. Admittedly PHP does require some more discipline than most languages and it doesn't look the most elegant, but there are certainly plenty of reasons to use it.
I'll give the example of an internal system I develop for an IT company. Technically, it could be written in whatever, but they explicitly wanted PHP, as do a great many businesses. Why? Because PHP is after plain HTML the absolute simplest to make a server for and if you want to host it externally, it's still simple and really cheap.
There is plenty of demand for PHP for other reasons, and these days, most of these codebases won't even be horrible spaghetti
I learned Spring, one of the worst frameworks I ever worked with (note that I have worked with Laravel too). Spring is a bloated mess with lots of legacy & misuse of annotations, a.k.a necromancy.
It has somewhat improved with Spring Boot, but still to be avoided.
Database layer in Spring, especially if you combine it with the monstrosity called Hibernate, is enough to apply to an insane asylum. Trying to debug what combinations of annotations that work and doesn't work is time you could have used writing PHP instead and get results.
The idea that you can annotate a SQL schema & query language into a Java class with annotations is one of the most asinine ideas I ever come across.
What language _isn't_ trying to be Java these days? What the old jargon file described as "bondage and discipline lanugage" applies to all major programming environments now, as Java proved that you can actually commodify programmers quite well and both old-school enterprises and the SV juggernaut need their harvest.
C#, TypeScript, Go, PHP -- they all converge on the same methods, tools and workflows. Tech choice these days is about what you want to have on your resume.
> You can actually commodify programmers quite well and both old-school enterprises and the SV juggernaut need their harvest.
At first we had guilds and craftsmen. We could only produce a few things, their quality was quite low and the products were expensive. This was one of the reasons quality of life was quite bad, actually.
Then we created the assembly line, standardized parts, mass production. Life sucked for the assembly line worker, but everyone else benefited. From a certain point of view even the assembly line worker benefited.
Hand crafting doesn't scale. 1 brilliant coder with in the Lisp Ivory Tower won't ever be able to reproduced the output of 100 decent covers in the Java Middleware Shop. It stands to reason, those decent coders can use their brains and time to test more, implement more kinds of features, talk to customers, colleagues, bosses, maybe even promote their product and do all sorts of things human beings do when they want something (coding is only a minor part of creating a successful product).
Two heads are better than one. And 100 heads that are not at loggerheads are better than two.
That's a whole bunch of items in one place. I don't disagree, to get better cooperation and efficiency in a group, languages and tooling have to adapt. That's part of my point, if what you're doing is the same, the languages will look the same.
But I quite disagree with the "it made our lives better" point, and would say that the efficiency, even with all the standardized language outlook, tooling and methodology is closer to the "9 women getting a baby in 1 month" quip than to Ford's assembly lines.
This is a bit too late, but for future reader's reference: I meant "mass produced software", regarding its benefits. I highly doubt that Facebook's ad network is comparable with mass produced pharmaceuticals or refridgeration. Mass produced mustard gas maybe.
Spring Boot and https://micronaut.io/ gets my job done. Thank you. Yes, I build web apps with Java so I don't have to waste my time with php. Life's too short. And I am old enough to remember the abomination Joomla was back in early 2000's and how horrible php was back then when my clients wanted to have their "sites" done in Joomla with custom plugins.
Spring Boot code is probably going to be less maintainable than PHP though. Added a new dependency? Congratulations, now your application behaves completely differently.
It scans the classpath and silently instantiates whatever it finds. E.g. you're depending on the mongodb client drivers? Congratulations, your spring context suddenly contains connections to mongodb servers. Upgrade one of your dependencies and the new version has a dependency on tomcat? Congratulations, your spring boot application silently starts running a webserver.
In effect this has an impact on performance but it also helps in ensuring that a bad request can't blow out the whole application from serving other requests like is common in platforms like nodejs where you need to be extra careful. Needless to say this makes php becomes quite viable for production envs, and prevents a whole host of issues that need expertise and careful programming to fix.