Modern PHP: New Features and Good Practices
Michael Ross writes In recent years, JavaScript has enjoyed a dramatic renaissance as it has been transformed from a browser scripting tool primarily used for special effects and form validation on web pages, to a substantial client-side programming language. Similarly, on the server side, after years as the target of criticism, the PHP computer programming language is seeing a revival, partly due to the addition of new capabilities, such as namespaces, traits, generators, closures, and components, among other improvements. PHP enthusiasts and detractors alike can learn more about these changes from the book Modern PHP: New Features and Good Practices, authored by Josh Lockhart. Keep reading for the rest of Michael's review.
Modern PHP: New Features and Good Practices
author
Josh Lockhart
pages
268
publisher
O'Reilly Media
rating
8/10
reviewer
Michael Ross
ISBN
978-1491905012
summary
Solid advice on some state-of-the-art PHP tools and techniques.
Programmers familiar with the language and its community may recognize the author's name, because he is the creator of PHP The Right Way, a website which he describes as "an easy-to-read, quick reference for PHP popular coding standards, links to authoritative tutorials around the Web and what the contributors consider to be best practices at the present time," in 21 different languages.
Yet rest assured that the book under review is not merely a dead-tree version of the website. Instead, the book covers the more recent advancements within the language, while the website covers best practices and standards. This should be borne in mind, otherwise the reader may be baffled by the absence from the book of certain topics on the website essential to the language, such as SPL, PEAR, and PHPDoc. Moreover, of the topics shared between the book and the website, the information is generally organized quite differently, with more example code in the book.
This title was published on 1 March 2015, under the ISBN 978-1491905012, by O'Reilly Media, who kindly provided me with a review copy. Its material is presented in 268 pages, organized into 13 chapters (The New PHP; Features; Standards; Components; Good Practices; Posting; Provisioning; Tuning; Deployment; Testing; Profiling; HHVM and Hack; Community), which are grouped into three parts (Language Features; Good Practices; Deployment, Testing, and Tuning) — as well as two appendices (Installing PHP; Local Development Environments) and an index. The publisher's page does not offer much of interest. However, all of the example code is available from the book's GitHub repository. There are differences between the GitHub code and what is printed in the book, e.g., a baffling require 'vendor/autoload.php'; in the first example code file. The author claims that the reader does not need to know PHP, but at least "a basic understanding of [] fundamental programming concepts" (page xiv). However, anyone without at least intermediate skills and experience with PHP could conceivably struggle with these more advanced subjects.
The first chapter is only a brief overview of the history of PHP, its current state, and some possible future changes to the language's engine. The real content starts in the second chapter, in which the author gives the reader a fast-paced introduction to his seven favorite major new features in PHP: namespaces, class interfaces, traits, generators, closures, Zend OPcache, and the built-in HTTP server. In some regards, the coverage is a bit too fast-paced, as some topics and questions likely in the reader's mind are not addressed — for instance, namespace case-sensitivity and techniques for ensuring that a chosen namespace is globally unique (page 9). For each topic, its purpose and advantages are explained, and sometimes illustrated with code examples, although none are extensive.
The second part of the book opens with a chapter on some of the new standards in the PHP ecosystem that are intended to move the common development process from a reliance upon one isolated framework, with an idiosyncratic coding style, to distributed components that can interoperate through the use of interfaces, industry-wide coding standards, and the use of autoloaders for finding and loading classes, interfaces, and traits at runtime. Components are covered in more detail in the subsequent chapter, as is Composer, for installing components and managing dependencies. The fifth chapter is a lengthy but information-packed exposition of numerous best practices regarding input data sanitization, password handling, dates and times, and safe database queries, among other topics. Some of the advice can be found in other PHP books and online, but all of this is neatly explained, updated with the newer PHP versions, and worthwhile as a refresher.
Deployment, testing, and tuning are the broad subject areas of the third and final part of the book. The author discusses the options for hosting your PHP applications, as well as provisioning any self-managed web server and tuning a server for optimal performance. All of the instructions assume you are using Linux and nginx, and thus would be of less value to those using Windows or Apache, for instance. The material on application deployment is relatively brief, and focuses on use of the Capistrano tool. Testing is often neglected in real-world projects, but certainly not in this book, as the author explains unit and functional testing, illustrated through the use of PHPUnit. This is followed by information on how to use a development or production profiler to analyze the performance of your application, with detailed coverage of Xdebug and XHProf, among other tools. The next two chapters dive into topics related to the (possible) future of PHP — specifically, Facebook's HHVM PHP interpreter and their Hack derivative language. The final chapter briefly discusses the PHP community. The two appendices explain how to install PHP on Linux or OS X for commandline use, and how to set up a local development environment. The author mentions a free edition of Zend Server, but the vendor page mentions no such pricing.
Despite its technical subject matter, this book is not a difficult read. The author's writing style is usually light and friendly, especially in the preface. In a few places, the phrasing is a bit too terse, which might prove momentarily confusing to some readers, e.g., "Function and constant aliases work the same as [those of] classes" (page 11). The text has some errata (aside from the two, as of this writing, already reported): "curl" (pages 15, 220, and 222; should read "cURL"), "a an argument" (page 33), "Prepared statement [to] fetch" (pages 99 and 100), "with [the] php://filter strategy" (page 110), "2 Gb" (page 129; should read "2 GB"), "the the" (page 154), "path to a the code" (page 176), and "Wordpress" (page 190; should read "WordPress").
One weakness with the book is that for several of the topics — including some critical ones — there is not enough detailed information provided that would allow one to begin immediately applying that technique or resource to one's own coding, but instead just enough information to whet one's appetite to learn more (presumably from another book or a website). Secondly, some of the narrative — particularly near the end of the book, when discussing various tools — would be of less value to anyone not developing analytics environment. Beware that some of the tools require numerous dependencies. For instance, do you have Composer, Git, MongoDB, and its PHP extension installed? If not, then you won't be using XHGUI. Also, some of the installation and configuration steps are quite lengthy, with no details provided for troubleshooting issues that might arise. Lastly, despite the promise that any reader with only basic programming knowledge will be able to fully understand the book, such a reader would likely find much of its contents mystifying without further preparation from other sources.
Nonetheless, the book has much to offer, despite its slender size. Numerous resources are recommended — most if not all apparently vetted by the author, who clearly has considerable experience in this arena. Some valuable techniques are presented, such as those instances in the text where the author shows how to use iteration on large data sets to minimize memory usage. In addition, the example code demonstrates that the author has made the effort to produce quality code that can serve as a model to others. Modern PHP does a fine job overall of explaining and advocating the newer capabilities of PHP that would attract developers to choose the language for building state-of-the-art websites and web applications.
Michael Ross is a freelance web developer and writer.
You can purchase Modern PHP: New Features and Good Practices from amazon.com. Slashdot welcomes readers' book reviews (sci-fi included) -- to see your own review here, read the book review guidelines, then visit the submission page. If you'd like to see what books we have available from our review library please let us know.
Yet rest assured that the book under review is not merely a dead-tree version of the website. Instead, the book covers the more recent advancements within the language, while the website covers best practices and standards. This should be borne in mind, otherwise the reader may be baffled by the absence from the book of certain topics on the website essential to the language, such as SPL, PEAR, and PHPDoc. Moreover, of the topics shared between the book and the website, the information is generally organized quite differently, with more example code in the book.
This title was published on 1 March 2015, under the ISBN 978-1491905012, by O'Reilly Media, who kindly provided me with a review copy. Its material is presented in 268 pages, organized into 13 chapters (The New PHP; Features; Standards; Components; Good Practices; Posting; Provisioning; Tuning; Deployment; Testing; Profiling; HHVM and Hack; Community), which are grouped into three parts (Language Features; Good Practices; Deployment, Testing, and Tuning) — as well as two appendices (Installing PHP; Local Development Environments) and an index. The publisher's page does not offer much of interest. However, all of the example code is available from the book's GitHub repository. There are differences between the GitHub code and what is printed in the book, e.g., a baffling require 'vendor/autoload.php'; in the first example code file. The author claims that the reader does not need to know PHP, but at least "a basic understanding of [] fundamental programming concepts" (page xiv). However, anyone without at least intermediate skills and experience with PHP could conceivably struggle with these more advanced subjects.
The first chapter is only a brief overview of the history of PHP, its current state, and some possible future changes to the language's engine. The real content starts in the second chapter, in which the author gives the reader a fast-paced introduction to his seven favorite major new features in PHP: namespaces, class interfaces, traits, generators, closures, Zend OPcache, and the built-in HTTP server. In some regards, the coverage is a bit too fast-paced, as some topics and questions likely in the reader's mind are not addressed — for instance, namespace case-sensitivity and techniques for ensuring that a chosen namespace is globally unique (page 9). For each topic, its purpose and advantages are explained, and sometimes illustrated with code examples, although none are extensive.
The second part of the book opens with a chapter on some of the new standards in the PHP ecosystem that are intended to move the common development process from a reliance upon one isolated framework, with an idiosyncratic coding style, to distributed components that can interoperate through the use of interfaces, industry-wide coding standards, and the use of autoloaders for finding and loading classes, interfaces, and traits at runtime. Components are covered in more detail in the subsequent chapter, as is Composer, for installing components and managing dependencies. The fifth chapter is a lengthy but information-packed exposition of numerous best practices regarding input data sanitization, password handling, dates and times, and safe database queries, among other topics. Some of the advice can be found in other PHP books and online, but all of this is neatly explained, updated with the newer PHP versions, and worthwhile as a refresher.
Deployment, testing, and tuning are the broad subject areas of the third and final part of the book. The author discusses the options for hosting your PHP applications, as well as provisioning any self-managed web server and tuning a server for optimal performance. All of the instructions assume you are using Linux and nginx, and thus would be of less value to those using Windows or Apache, for instance. The material on application deployment is relatively brief, and focuses on use of the Capistrano tool. Testing is often neglected in real-world projects, but certainly not in this book, as the author explains unit and functional testing, illustrated through the use of PHPUnit. This is followed by information on how to use a development or production profiler to analyze the performance of your application, with detailed coverage of Xdebug and XHProf, among other tools. The next two chapters dive into topics related to the (possible) future of PHP — specifically, Facebook's HHVM PHP interpreter and their Hack derivative language. The final chapter briefly discusses the PHP community. The two appendices explain how to install PHP on Linux or OS X for commandline use, and how to set up a local development environment. The author mentions a free edition of Zend Server, but the vendor page mentions no such pricing.
Despite its technical subject matter, this book is not a difficult read. The author's writing style is usually light and friendly, especially in the preface. In a few places, the phrasing is a bit too terse, which might prove momentarily confusing to some readers, e.g., "Function and constant aliases work the same as [those of] classes" (page 11). The text has some errata (aside from the two, as of this writing, already reported): "curl" (pages 15, 220, and 222; should read "cURL"), "a an argument" (page 33), "Prepared statement [to] fetch" (pages 99 and 100), "with [the] php://filter strategy" (page 110), "2 Gb" (page 129; should read "2 GB"), "the the" (page 154), "path to a the code" (page 176), and "Wordpress" (page 190; should read "WordPress").
One weakness with the book is that for several of the topics — including some critical ones — there is not enough detailed information provided that would allow one to begin immediately applying that technique or resource to one's own coding, but instead just enough information to whet one's appetite to learn more (presumably from another book or a website). Secondly, some of the narrative — particularly near the end of the book, when discussing various tools — would be of less value to anyone not developing analytics environment. Beware that some of the tools require numerous dependencies. For instance, do you have Composer, Git, MongoDB, and its PHP extension installed? If not, then you won't be using XHGUI. Also, some of the installation and configuration steps are quite lengthy, with no details provided for troubleshooting issues that might arise. Lastly, despite the promise that any reader with only basic programming knowledge will be able to fully understand the book, such a reader would likely find much of its contents mystifying without further preparation from other sources.
Nonetheless, the book has much to offer, despite its slender size. Numerous resources are recommended — most if not all apparently vetted by the author, who clearly has considerable experience in this arena. Some valuable techniques are presented, such as those instances in the text where the author shows how to use iteration on large data sets to minimize memory usage. In addition, the example code demonstrates that the author has made the effort to produce quality code that can serve as a model to others. Modern PHP does a fine job overall of explaining and advocating the newer capabilities of PHP that would attract developers to choose the language for building state-of-the-art websites and web applications.
Michael Ross is a freelance web developer and writer.
You can purchase Modern PHP: New Features and Good Practices from amazon.com. Slashdot welcomes readers' book reviews (sci-fi included) -- to see your own review here, read the book review guidelines, then visit the submission page. If you'd like to see what books we have available from our review library please let us know.
Best practice for PHP: don't use PHP.
(correction with the slashcode) ...
Speed
PHP has been
Even Wikipedia's transitioning from PHP to Lua.
[citation needed]
http://blog.wikimedia.org/2013... (not that I beleive in Lua)
The best practice for using PHP: don't use it at all!
....PHP enthusiasts and detractors....
Who is this PHP "enthusiast" and how many drugs does he take to maintain this elaborate illusion...
Good people go to bed earlier.
Blaming the language for bad code is asinine. Blame bad (or inexperienced, or just plain lazy) programmers. I write PHP stuff. I also write Perl, C, C++, C#, Pascal, JS, and recently VHDL. I have written Java and Ruby code as well, but no longer do. Overall PHP is only as bad as the developer makes it. If I could change one thing about it, it would be getting the built in functions more consistent in return types and argument order for similar functions. I'm constantly referring to the documentation because for some particular functions I can't remember if haystack or needle comes first, for example.
It gets the job done quickly and easily, and if you find or write a good foundation of libraries and classes, the code is elegant and easy to understand as well. Just like every other language.
That post is about enhancing their wiki code templating language, not switching away from PHP. The only thing they're switching is to HHVM, which is still PHP code.
http://blog.wikimedia.org/2014...
after years as the target of criticism, the PHP computer programming language is seeing a revival
PHP has a really bad reputation, probably well-deserved. I don't know if it can overcome that at this point.
It can be implemented well. I have seen it. The trouble arises when folks insist on over-engineering their PHP solution. I won't mention the photo project, but one time I was looking for the value of a variable. After days of grepping and sifting through thousands of lines of code, I found out that this variable was nothing but a constant in a very deeply embedded class structure. Why they created this whole class and derivatives just to set a constant, I can only guess that they freebased the OOP Kool-Aid.
I don't give a shit what your CS prof says, there is nothing wrong with defines. Or 'goto's for that matter. There's nothing more annoying than a method/function that's hundreds of lines long just because the programmer didn't want to use a 'goto'.
I'm guilty too because I was shamed one time when I used it. But, where I worked, our productivity was counted by KLOCs. So, it all worked out.
I don't get this it's-never-the-tools-but-always-the-programmer attitude that you have. I've seen it a lot at Y Combinator's Hacker News site, too. It's really a dumb concept.
Some tools are inherently bad, and irreparably broken, even in the hands of the most skilled and experienced practitioners.
Even the best master carpenter can't use a blob of Jello as a hammer or a saw. That doesn't mean the carpenter is no good. This carpenter is the best there is. He's just using a totally inadequate tool.
It's the same for programmers using PHP. PHP is naturally broken in ways that even the greatesr, most skilled programmers can't suitably deal with. PHP is just a bad tool in anyone's hands.
I'm not down with Other People's PHP (OPP), knaw me
the only permanence in existence, is the impermanence of existence.
I've written PHP, Java, Javascript, C#, C++, C, and VB (and have dabbled in Ruby and Python), and I still don't get the hate for PHP. Granted, weakly-typed variables are a bit aggravating, but that's the only major complaint I have with it.
"People who think they know everything are very annoying to those of us who do."-Mark Twain
Some small examples: http://eev.ee/blog/2012/04/09/... and many of http://www.reddit.com/r/lolphp...
Honestly I'm really tired of reading over and over again about how PHP is bad and is better. I'm working for one of major European companies that have e-commerce businesses all over the world and pretty much everything is developed in PHP. Properly developed. Currently we employ around 3000 devs worldwide and somehow the products are stable, reliable and security wise, we still haven't had much issues except for some mishaps from system administration side. Our code is not all written from scratch because we employ some frameworks that indeed force most of the people to write better code.. Add constant code reviews from professional team leads, some tools that help you hunt bugs and you get yourself a proper platform. And I've seen it all.. Java development, C for embedded systems, .NET for medical development. There is shit everywhere when there is no discipline, so please spare me all the mocking. Don't blame the tool.. blame your laziness for not doing things properly.
Fucking a fat girl is like riding a scooter... it's fun 'til someone sees you.
Real programmers create web technologies using FORTRAN. Fuck all this API object-oriented horseshit.
A lot of that can be alleviated simply by having a language that does not overload operators across types, such as "+" for addition and concatenation, and by having optionally type-validated parameters.
ColdFusion may suck in other ways, but it got these two things mostly right. Witness the function parameter (argument) declaration definition:
Example code:
You don't have to declare type and required status if you don't want to, but the feature is there IF you want tighter typing. (There is no compiler to check up-front, it's still dynamic, but I imagine a "lint" like warning system could be built that can spot suspicious type usage before a run.)
Note that ColdFusion has no (detectable) type "tag", and validation is done by parsing, or what resembles parsing. It perhaps may use tags under the hood for performance reasons, but they are not visible to programmers. (Thus, a clone interpreter without tags would produce the same result, ignoring performance.)
That simplifies things in my opinion. It's "WYSIWYG" typing. Tag-based typing is trickier to manage in my opinion. I much prefer tag-free (including my mattress). ColdFusion thought dynamic typing through.
Table-ized A.I.
The comments on this article are a horrible cesspool worthy of Youtube commenters.
PHP hatred is the in thing, I get it. But what do these comments have to do with the fine article? How are we improving as an industry by hating on PHP? How are we encouraging the next generation of coders by these vapid, ignorant comments?
If you agree, I invite you to join the rest of us Slashdot refugees at HN. Ouch. So sad.
This is mostly because there are few practical alternatives on the client side. You can't have the user install say Python on the client side if you want to use Python. It's the QWERTY of programming languages: you are stuck with it because everybody else is also stuck with it. They are not going to fudge their browser just for your particular site.
While JavaScript may be fine for a light-duty glue language, it sucks big juicy ones for large interconnected libraries, such as GUI engines. A strong-typed language is much better suited for large libraries.
It's backwards to load an entire GUI engine just for one app. It's almost as bad as DLL-Hell. Time to rethink web GUI standards (or lack of).
Table-ized A.I.
I found the install of php on windows to be so much of a pain in the ass that I avoid it for that reason alone. No linux here... can't get it onto a unix box.
This mismatch of httpd and php situation is terrible.
ORLY?
I've never seen PHP in decline at all. People still rolling out Wikimedia Wiki's and Wordpress sites like there's no tomorrow.
A lot of BS about PHP comes from developers of more OOP/MVC coding designs using Ruby on Rails, where as I think Ruby on Rails is a mess.
PHP lets developers do what they want to do, if that means combining html and a pile of includes to use it as an efficient SSI, so let them. That's what it's really good for.
What PHP is really bad for is beginner developers who put stuff on the web without taking into consideration security (never use $_GET directly in a SQL query for example)
now all of you haters can properly go fuck yourselves.
For all of PHPs many, many horrors, the one that actually got me the most is the lack of static typing when working with a large body of PHP code (Wordpress). One can wonder at many of the details of arrays etc, but once you know all the gotchas then you can work with them. But no static typing gets you over and over.
It is also interesting that 40 years of careful research into programming language design, including very sophisticated systems such as Algol 68 and Common Lisp, had absolutely no effect on the design of what are the most commonly used hack languages today. (PHP and C.)
and, yeah, I'm sick of php but still writing it
I CAN tell you why PHP 3.x and 4.x were used in a lot of projects with security problems. I've made many posts here going into detail. The biggest thing was probably autoglobals. That was insane for a WEB language, even one then intended to be easy. It might make sense for local macros (vbscript) that are supposed to be written by non-programmers.
If you combined few of PHP 4.x blind spots with stupid Plesk running the script via suexec, you either found out you quickly got owned, or more often got owned and didn't even know it.
PHP really sucked in terms of security and there were several very clear reasons for that. Some will say even old PHP could be used to write secure software. Nope, not with the default PHP.INI configuration. Even a blank, empty PHP script contained a significant security risk.
Things are MUCH improved. People who actually know something about language design have gotten involved. Rasmus has said publicly that he doesn't know anything about language design and early versions of PHP proved that. Of course, he wasn't originally creating a programming language, PHP was a CMS, written in Perl. It was ABused as a general purpose programming language, and it didn't do a good job in that role, because it wasn't designed for that role. The newer versions ARE designed as a general purpose web programming language, and they are much better suited to the task.
A lot of BS about PHP comes from developers of more OOP/MVC coding designs using Ruby on Rails, where as I think Ruby on Rails is a mess.
look at the mess calling the mess a mess!
Don't.
I do not fail; I succeed at finding out what does not work.
Don't use PHP. Use node. If you can't do that, use C. Not C# or C++, C. What, are you eight or something?
Need Mercedes parts ?
Comment removed based on user account deletion
Ohhh come on ! It's 2015, and this is still true: http://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/
Disclaimer: I didn't write this, but it summarizes pretty much what I thought of PHP.
(the incoherent libraries are a show stopper for me)
JavaScript opens doors to browser-based attacks http://news.cnet.com/JavaScrip...
Fact: Javascript's DOM model is fucked.
So, don't even try to tell us that completely utter bullshit webboy. Your "Web 2.0" is purest bullshit and a privacy nightmare too!
I can literally post another 55++ like articles here easily with more specific javascript driven exploits.
The problem?
You web dumbos are not real programmers. That's right. You have no clue. If you're not aware of javascript's issues, you're clueless. Period.
Dimwits like yourself don't realize a lesson from history. Microsoft's history of all places. The second you introduced scripting into documents (ala Word, or Excel macros in their compound object document model to attempt to be a datacentric, rather than app centric model)? The trash came blowing in.
Is scripting web documents any better? Read the article above, tell us differently.
Attempting to spout b.s. to further your agenda & 'career' now? It's not working vs. fact. It's that, in your utter lies, or you are ignorant of history.
PHP has earned all the scorn it gets and than some.
It is developed by amatuers, for amatuers.
I am glad it exists because its exsistence on a resume gets it deleted with prejeduce.
Sure there might be one or two programmers worth hiring with PHP on their resume, but I would rather miss those two than have to deal with 100,000 PHP cretins to find them