26 ms·
PHP: The Right Way
- wseymour 14y agoI think that Lithium (www.lithify.me) would be really great to mention under the 'popular frameworks' section.
- codeguy 14y agoThanks for the suggestion. Feel free to send a pull request and I'll be happy to add it in!
- rickmb 14y agoStraight, simple and to the point. Nice. Missing test and QA tools though. Probably an oversight, since the author does suggest following Derick Rethans and Sebastian Bergmann. And another one: read up on the SPL library before you start re-inventing that wheel.
- codeguy 14y agoAll good points. If you'd like to submit a pull request, I'll be happy to credit you with the additions and get them added to the site.
- wyclif 14y agoThis is a great idea. Quick grammar correction under Introduction>Input Filtering: remove the apostrophe from "That lead's to dark and dangerous places."
- deleted 14y ago[deleted]
- TylerE 14y agoSomething to consider mentioning - there are some in PHP these days that take this sort of stuff a bit too far. Drives me nuts to see people writing classes to encapsulate a 3 column database result. So much overhead and boilerplate.
- timaelliott 14y agoYou should check out Java sometime.
- TylerE 14y agoThat's exactly my problem with it. It's just that when you do in PHP, you don't get any of the benefits you derive from all the Java BDSM.
- timaelliott 14y agoJava still gives me nightmares ;(
- pjmlp 14y agoThe problem is not Java, but some types of architects that flourish in corporations, usually doing designs with endless numbers of abstractions, layer upon layer. I've seen this happening in C, followed by C++, and now Java and C#. They will do it regardless of the language being used.
- timaelliott 14y agoThis is an excellent point. I so often attribute my disdain to Java itself when, in reality, the issue is the majority of Java engineers. Java itself can be a beautifully terse language.
- akavlie 14y ago"terse" is about the last word that I would use to describe Java. Compared to almost every other language I've had exposure to, it's more verbose.
- MartinCron 14y agoI usually don't like to put "beautiful" and "terse" next to each other. "expressive", maybe, but terse? That sounds like an insult.
- leke 14y agoNice read. TIL I should be doing some things differently in PHP.
- _ikke_ 14y agoI'm wondering why a specific code style is 'enforced' while it has nothing to do with interoperability. Libraries with different code styles can be used together without problems. It seems like they are using the PSR to declare they're own style as superior.
- codeguy 14y agoI think it's less about being "superior" than standardizing on a common style. Makes it easier to get up and running with someone else's code. But if your team agrees on a common but different style, that's fine too. It accomplishes the same goal. I'm only suggesting the official standard for new PHP developers.
- kellishaver 14y agoRight. I think the main take-away from it is to be consistent and make sure everyone on your team is on the same page about the coding style. I see the PSR as a basic set of good recommendations, rather than something that must be followed. It's a good idea to follow it, but at least follow something. My only complaint with it personally is that I Can. Not. Stand. putting opening brackets on their own line.
- mgkimsal 14y agoI understand it's not an either/or situation but... I'd MUCH prefer people spend time writing tests for their code vs debating/arguing/refactoring code style. If your tests and good and coverage is high, there's far less chance I should ever even have to muck around inside your libraries, much less modify them. And again, one doesn't preclude the other, but I see so many people making a bit stink over style - tabs vs spaces et al years before the PSR stuff - yet rarely do I see even 20% of that effort spent on getting people to test. I say this not as someone who tests everything 100%, but as someone who doesn't do much of it, and understands the importance of it. When I'm deciding to use someone else's libraries, I never make a decision based on the code style they've chosen - I base it on maturity, documentation, and tests/examples provided (when there's a choice, sometimes you don't have a choice, or you roll your own). The really good libraries? I never even have to look a their code - it might be all run together on one line for all I care - it just works.
- erikb 14y agoI like it. Would be smart to add some kind of picture for sharing Facebook is more successful if people not just see text.
- erikb 14y agolol. downvotes for wanting to share someone's idea. that one I really don't get...
- mikeash 14y agoProbably because your comment is extremely difficult to understand and looks a lot like spam.
- erikb 14y agoWhat is hard to understand about it? Most link sharing happens on facebook. If you share a link in facebook, people will click on it, IF there is a picture that interests them. If there is no picture 99% of people will ignore the shared link. So for the author of this website it would make sense to add any picture at all. When someone shares the link to his website, FB will automatically find the picture. But there is none.
- mikeash 14y agoWhat's hard to understand about it is that it's a mishmash of words thrown together with no coherency. Your point about having an image to make Facebook sharing makes sense, but there's no way to extract that point from your original post.
- erikb 14y agoThere is a dot missing between "sharing" and "Facebook". I just see that now. If there are more grammar issues, I am always open to learn. It's not my mothertounge, though. And I think I have that attribute in common with a lot of readers here...
- xd 14y agoHey, nice work. Wouldn't a wiki platform work better however, instead of git? Edit: also might be worth adding a bit about steering clear of phpclasses.org as well as w3schools, they bother contain far more bad, than good code.
- codeguy 14y agoWill be moving over to GitHub pages w/ Jekyll soon to automate build process.
- AmaralHerberth 14y agoGit (along with Github) may be better because of the higher control that you have over the development/writing with a not-so-high management work (you don't even need to have a git client in order to change content since the content is hosted on Github). It is easier to manage different versions, apply patches and so on. Dokuwiki might work well for this purpose because its (almost) 0-config setup, though.
- BadCRC 14y agoThese guidelines won't save you from some bullshit PHP "rules", such as: http://stackoverflow.com/questions/5810168/php-foreach-by-reference-causes-weird-glitch-when-going-through-array-of-objects http://stackoverflow.com/questions/5810168/php-foreach-by-re...
- xd 14y agoHow is that a "bullshit PHP rule"? If you for loop in C, setting a pointer each iteration, you would expect the pointer to still be set the the last assignment in the loop once you're out of it.
- LnxPrgr3 14y agoC lets you define variables with block scope: int main(int argc, char *argv[]) { for(int i=0;i<10;++i) printf("%d\n", i); printf("%d\n", i); } The last line fails to compile—'i' is no longer defined after exiting the loop. Java: public static void main(String[] args) { for(int i=0;i<10;++i) System.out.println(i); System.out.println(i); } That also won't compile. Coming from a language that supports variables with block scope, PHP's behavior is very surprising indeed. If the first mention of $object is in the loop, I can understand someone expecting $object in the second loop to be a distinct variable that just happens to share the same name. This behavior is even surprising coming from Perl, though for a slightly different reason: @array = ('c', 'c++', 'java', 'perl'); foreach $item (@array) { if($item eq 'perl') { $item = 'php'; } } foreach $item (@array) { print $item . "\n"; } For that matter, PHP's reference semantics are a little surprising in general coming from any other language I've ever used.
- xd 14y agoI was thinking more of: #include <stdio.h> int main() { int arr[10] = {1,2,3,4,5,6,7,8,9,0}, *ptr; for(int i = 10; i>=0; i--) { ptr = &arr[i]; printf("%d\n", *ptr); } printf("%d\n", *ptr); }
- postfuturist 14y agoAs a part-time PHP hater who often has to work with it professionally, I believe this is a fantastic resource. The bit on databases in particular is something that all PHP devs should read. That said, it is difficult to bring a legacy code base in line with modern style, though you can improve it over time. Also, this could benefit from some other gotchas, extremely surprising behavior and best practices for avoiding common pitfalls.
- grakic 14y agoOn a database section, I am not a fan of PDO and I choose native interfaces like mysqli for my DAO layer or opt for something high level like ORM depending on the requirements. But it goes without saying that protection from SQL injection is a must, it is just PDO's statement binding is not the only way. MySQLi does support data binding, and for others it is easy to DIY using sprintf and whatever is the escaping method target native driver implements.
- astrodust 14y agoDIY and SQL are not two things you want to see together.
- swivelmaster 14y agoYou can use PDO to connect and run queries without using all the crazy variable binding features.
- kingkilr 14y agoOne point in and its already dead wrong, you never filter input, only output. Edit: Everyone talking about databases: paramaterized queries, check them out.
- codeguy 14y agoI'd definitely filter input that goes into a database. But if you think the wording can be made better, definitely send a pull request. Thanks!
- xd 14y agoSQL injection attacks alone are almost always a result of not filtering input...
- FuzzyDunlop 14y agoIt's sometimes known as sanitising input, so I'm guessing that's what they were trying to refer to.
- kellishaver 14y agoWith parametrized queries, that becomes a non-issue, but I still see no point in cluttering the database with data that's just going to be filtered out at some point - might as well filter it before it goes into the DB to begin with. The exception, of course, being those rare cases when some users need to see the filtered data and others need to see the raw data, but even then, you likely won't want to allow everything.
- silentworks 14y agoI am not sure if you are referring to the same sort of filtering mentioned in the document. The data is filtered before it hits the database layer, this saves resource being used.
- kellishaver 14y agoThat's what I meant. I just kind of articulated it poorly, my apologies.
- btbytes 14y agoI suggest that you open up the doc source on github so that you can attract contributions from people while still maintaining editorial control. A good example is: python-guide.org -- http://docs.python-guide.org/en/latest/index.html http://docs.python-guide.org/en/latest/index.html
- deleted 14y ago[deleted]
- codeguy 14y agoAs mentioned elsewhere in the comments, I'll be moving over to GitHub Pages tonight to do exactly this.
- silentworks 14y agoThere is a bit in the Introduction section of the doc that says how to contribute. Its actually just a one page on github at the moment that you can fork and send in pull request.
- nikic 14y agoI like the general idea of this, but think that it is nearly useless in its current form. It's way too superficial. To teach newbies how to do things right it doesn't suffice to link to a few resources and hope that they'll read them (hint: they won't). Instead one needs more concrete code examples, etc. Which would obviously be too much for one page :)
- codeguy 14y agoI agree. It's very much in a v1.0 form right now. Once I move over to GitHub Pages, I hope to add more links to tutorials and code samples without bloating the document itself.
- ericd 14y agoI think it offers a great starting point, though, and even though I've worked in PHP for a few years, I filled in a couple gaps in my knowledge. Thanks very much.
- derekerdmann 14y agoIf you have ideas, the author points out that he's accepting contributions from the community: https://github.com/codeguy/php-the-right-way https://github.com/codeguy/php-the-right-way
- nichodges 14y agoAs someone who taught themselves enough PHP to get by over the last 7-8 years, this is brilliant. I don't spend every day keeping up with the latest developments in PHP, but I know in that time the techniques I'm using must be out of date. I've learnt JQuery and Python lately, but my Swiss army knife is still PHP. So this has already fixed a lot of incorrect techniques I've been suing in a side project.
- pjmlp 14y agoThis is a very nice guide for everyone that has to work with PHP.
- avstraliitski 14y agoThe important parts of this eventually come to experienced programmers. I would favour a version of this document that included those with justifications. The less important parts (number-of-spaces-per-indent, somebody's camelCase method preference, etc.) should be pruned. An interesting effort, but really, do we need more 'standards'? Only real way to enforce coding standards: pre-commit hooks on your revision control server. http://xkcd.com/927/ http://xkcd.com/927/
- aw3c2 14y agocurl -s http://getcomposer.org/installer http://getcomposer.org/installer | php is creepy. Never ever run other people's code without at least giving it a glance.
- codeguy 14y agohaha. Always good advice. But I checked. It's fine :)
- chrismsnz 14y agoIt's fine now until someone hacks their site or poisons their DNS.
- anthonyb 14y agoOr writes a script which checks the user agent and only serves up malware to curl. Or the second time that an IP address hits it. Or something else that you haven't thought of. Update: Such as doing something nasty to http://getcomposer.org/composer.phar http://getcomposer.org/composer.phar instead - a 520KB php file that the first script downloads and runs without even md5ing first. Did you audit that too? Did you understand everything that it was doing?
- larrys 14y agoOr social engineers their registrar and changes their dns.
- zdw 14y agoRVM's installation is similar: https://rvm.io/rvm/install/ https://rvm.io/rvm/install/ A far cry from the safer/verified "download this and check it's MD5 checksum" method that I'd prefer. Seriously, fixing package management so we can continuously integrate arbitrary code would be great. Getting arbitrary OS package creation to be almost as easy as pushing code to GitHub seems like a very worthy goal.
- anthonyb 14y ago
- lukifer 14y agoWhile PSR-1 has pretty good universal guidelines, PSR-2 goes too far in insisting on subjective preferences (spaces over tabs, 80-char lines, bracketing styles). We should not pretend that there is a "correct" answer to these choices, just as long as they stay consistent on a per-project basis. All told, I love site, and I hope it keeps iterating. PHP may be ugly, but it's powerful, and most of its bad reputation comes from good coders having to pick up the pieces from bad coders.
- Jebus 14y ago+1 , I still don't know where this 'spaces over tabs' crap comes from. My guess is that it is good for things that must be done from a console (as opposed to using an IDE). But it has no place in PHP. Tabs + spaces break on different configurations? It's not because of tabs, it's because of spaces! Tabs are flexible, spaces are not. What's next, will I be forced to use a particular font size too?
- robertpateii 14y agoPSR-2 isn't trying to say that there is one correct answer. Instead they're trying to provide a single answer from the many valid possibilities. "When various authors collaborate across multiple projects, it helps to have one set of guidelines to be used among all those projects"
- chrismsnz 14y agoExactly, this is what infuriates me about the arguments and whining against PSR-2. Spaces, Tabs, OTBS, whatever. It doesn't matter which one was chosen, just that something was chosen. Ask the Pythonista's what PEP8 did for their developer's ecosystem. Also it's important to note that that PSR-2 was based off already existing coding standards like Zend's and Symfony's.
- lukifer 14y agoAnd what do you do with all the coders like me who would refuse to change their habits? Does the Python community have tabs holdouts who are github lepers because no one wants their code "infected"? (I don't do much in Python, I actually don't know what the community norms are.) I think it's silly to pursue per-language consistency; it's a pipe-dream that just leads to more religious wars over minutia. Per-project (or per-organization) more than suffices.
- kaolinite 14y agoReally hope they fix the formatting. Unreadable for me, the font is way too big.
- kaffeinecoma 14y agouser: kaolinite 20 year old Python/PHP/C developer That font will be just perfect for you in about 15-20 years.
- pestaa 14y agoI'm 20 too and always read articles with 300%-500% zooming if there is no vertical scrollbar. Occassionally putting the glasses down and still be able to read is a huge relief!
- kaolinite 14y agoIn 15-20 years, I will zoom as required. The issue really is less the font size and more the way the text stretches to the window, so if you zoom out then the sentences become far too long. I ended up having to alter my browser window size. Edit: Just checked, definitely just the stretching, though a bit smaller would be better for me.
- bjt 14y agoTangentially related: Smashing Magazine recently did an outstanding article on readable web typography. (See http://www.smashingmagazine.com/2012/05/02/applying-macrotypography-for-readable-web-page/ http://www.smashingmagazine.com/2012/05/02/applying-macrotyp...). They say 8-12 words per line is ideal, though their example exercise seems to average closer to 15.
- Luff 14y agoHold ctrl and use the scroll-wheel on your mouse to zoom in and out.
- jimmytucson 14y agoI didn't understand this: 4.2. Properties This guide intentionally avoids any recommendation regarding the use of $StudlyCaps, $camelCase, or $under_score property names. Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level. 4.3. Methods Method names MUST be declared in camelCase().
- jasonlotito 14y agoWhat don't you understand specifically? It can't be any clearer, and it's obvious the reasons for this with what the PSR is. So, I'm confused as to what you find confusing?
- RobAtticus 14y agoMethods should be camelCase(), but properties (fields?) can be any convention as long as its consistent throughout.
- jimmytucson 14y agoYup, that's my basic reading comprehension dropping out again. Thank you, that does make sense.
- ecocentrik 14y agoIt looks clear to me. Properties refer to object properties or variables and Methods refer to object methods or functions. This standard recommends three formating conventions for variable names and requires that all functions be written in camelCase.
- gbog 14y agoPHP with these guidelines looks like JAVA to me, but without the relatively sane foundations. It is fun how much a very old moralist sentence by Confucius applies well to PHP. He said 其本亂而末治者否矣 which can be translated, in software language development context, as "Build a nice, reliable language on shitty definition? Bullshit!". (The word-by-word translation is "your - root - messy - and/but - leaves/result - governed/orderly - have ? not - hey!") This sentence also resonates with the odd Turkish encoding PHPbug recently reported here: if you have so many wrong architecture decisions in the core of your product, no amount of patching and "under the rub" filling will save you. Edit: added word-by-word translation + typo fixes.
- billpatrianakos 14y agoWe get it, man. PHP sucks, you're cool/smarter/better because you use something else, and you need to remind us all about it by jumping in every time the letters P-H-P are seen in sequence to let us all know how it sucks by retreading the same old lines used by the last fifty guys who said the same thing but to your credit you really tried to be clever about it. A good portion of why people like to mock PHP is due to the way people end up using the language rather than the language's ugly parts. This guide is a great step toward pointing people in the right direction with the language. PHP has come a very long way and continues to improve. A big chunk of the battle is having decent guides to replace all the crap that's out there showing new PHP devs the wrong way. So why not talk about the merits of the guide rather than taking an easy opportunity to shit on PHP. It's really gotten old. Hey, remember when JavaScript was like the worst language ever and everyone felt the need to remind everyone about that constantly? I do. And now all of them are writing blogs about how awesome node.js is.
- mikeash 14y agoYes, how dare he talk about the problems with PHP in the comments on a site dedicated to talking about how to avoid problems with PHP. Seriously, WTF? Are people actually offended that discussion of PHP's defects take place in a conversation about PHP best practices?
- 14y ago
- ObnoxiousJul 14y agoRight way to write PHP indeed. Sometimes I wish PHP itself was written this way. Oh! The guide does not mention the case: if a class contains only one static method, please, use a function. It does not look as educated, but it's obviously a function. Not PHP specific, I admit.
- lotyrin 14y agoOh god yes. I ran into an extreme case of this recently. 200 something lines of class definition, class variables and internal private methods that end up chaining 5-deep, with a single public method. Refactoring to a single function took it down to under 20 lines. I wish I knew what motivated people to do things like this.
- etherealG 14y agopretty sure it's the same thing every time: coming from working on really big systems that need that much depth of abstraction to something simple that can be done in 20 lines and forgetting, or not understanding how to scale down. most common with c# or java coders doing client libs for php for their application.
- FuzzyDunlop 14y agoFrom my own experience, PHP developers who are introduced to OOP often get taught the Java-esque flavour of it. Classes for everything, abstractions and base classes and inheritance all over the place. Hell, I even went there myself at one point, at first doing it to DRY up a bunch of procedural scripts, but later introducing more abstractions to bend the existing code to my will. Now, I prefer simplicity and will often scrap code that jumps through all sorts of hoops just to do something simple.
- mgkimsal 14y agoIt would depend on what else is in the class - descriptive class constants used by the one static method wouldn't be possible if it was 'just a function'.
- ChiperSoft 14y ago
- etanol 14y agoThe comments about namespace are somehow ironic: is it very common to find developers that know what classes are but not namespaces? The namespace concept is much simpler than class. Which makes me wonder: who is the target audience?
- jmadsen 14y agopossibly. Namespaces are very new to php, so programmers who taught themselves via php might not have much experience using or general knowledge of them
- ChiperSoft 14y agoIt's only been in the last 2 years or so the php web hosts have upgraded to version 5.3, which is when namespaces were added. There are a LOT of long term php developers who have never used them.
- pjmlp 14y agoWhat I hate about namespaces in PHP is the separator they have chosen \.
- socratic 14y agoAre there any good books (or other resources) on modern PHP? I last used PHP back with PHP3 (and then went C++ => Java => Python => Python/JavaScript => Ruby => Python/R), but a bunch of code I want to read at work uses PHP (with Zend). I no longer remember most of what I learned about PHP3, though obviously the PHP syntax seems to be at least somewhat readable as a sort of amalgam of Perl and C++ syntax and idioms. What does, e.g., Facebook use to get engineers who don't know PHP (but might know C++ or Python) up and running?
- nbm 14y agoAs far as I know, at Facebook we don't give pre-emptively/usually give people a book to learn PHP. Those that don't know PHP (or are rusty) can generally get the syntax/keywords right in an hour, and then there's a longer time spent getting familiar with both the standard library and our own frameworks/libraries. There is a lot of good code to look at and learn from, and the Bootcamp program teaches a bunch of our own library and some guidance on what good and bad standard library functions are for certain cases. We also have a "newbie" group where people can ask questions about the codebase. And if you do something without knowledge of a built-in (or Facebook) function/class and make things more complex than they need to be, your code reviewer will let you know how to do it easier/more idiomatically. Every once in a while there are language tech talks, and sometimes even whole-day training sessions (we did one on exciting new C++11 features). Besides that, I definitely spent a lot of my time with php.net/function_name open and exploring when I couldn't remember all the functions available or the parameters and order.
- healsdata 14y ago"Real-World Solutions for Developing High-Quality PHP Frameworks and Applications" by Sebastian Bergmann (referenced in the original article) and Stefan Priebsch. It won't go in to things like "how do I use usort" but it touches on important things like testing.
- FixThisPOSSite 14y ago"Method names MUST be declared in camelCase" Doesn't make sense. Most method and function names are sentences, and thus should start with a capital letter. ParseInput LogError ComputeTimeRemaining
- whalesalad 14y agoI think in order to prove PHP's worth we'll need to collectively redevelop a modern PHP webapp cookbook. I'd like to see something like that myself. I still enjoy writing PHP (partly due to nostalgia) despite it's wealth of flaws.
- sneak 14y agoPHP: Not even once.
- deleted 14y ago[deleted]
- stephenhandley 14y agohttp://jeena.net/images/2012/PHP-The-Good-Parts.pdf http://jeena.net/images/2012/PHP-The-Good-Parts.pdf
- DCoder 14y agoThere's an easier-to-read version for those who don't like PDF: http://jeena.net/images/2012/php-the-good-parts.jpeg http://jeena.net/images/2012/php-the-good-parts.jpeg :-)
- gabordemooij 14y agoI dont agree with the article all the way but it's certainly refreshing to see people trying to improve PHP coding practices instead of just complaining. Very well done. That being said... Every language has its strengths and weaknesses. There is nothing fundamentally wrong with PHP (except maybe that if you look at it it's not a very exciting language, even a bit boring). Security for instance has nothing to do with the language itself. And as for PHP syntax, it's a blessing compared to some other languages; at least we don't have a semicolon debate in PHP land ;-)
- countessa 14y agothis is great stuff - I'm a casual php hacker and this is just the sort of thing I need to help me out when I'm working in the language - saves me from having to be deeply embedded in the culture of a language I don't use "all day every day"....so thanks!
- Morg 14y agoIf only the people giving advice knew what they were doing ... - php's filter functions : useless, you'll end up cooking up some regex anyway ( be it manual or metadata based) - pdo ? why ? native drivers can be just fine - binding parameters instead of sanitizing ? want another hammer maybe ? everything looks like a nail to you obviously. - password hashing. why should it take place in php specifically when it's one of the slowest layers - and when you could ask the dbms to do it - it's a design choice but are you making the right one ? Once again . don't call it "the right way" if you don't know the right way, mkay.
- aichi 14y agoWhy the hell is required space indentation instead of tabs? Don't you know how to setup your editor? Don't you know that there are coders with special needs and they would like to setup another indentation, because they are using e.g. font size 20px to see your code?