Slashdot Mirror


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.

22 of 182 comments (clear)

  1. Best practice for PHP... by Anonymous Coward · · Score: 2, Insightful

    Best practice for PHP: don't use PHP.

    1. Re:Best practice for PHP... by Anonymous Coward · · Score: 5, Funny

      Best Practice to make PHP run fast:

      Run. Fast.

  2. im skeptical... by nimbius · · Score: 4, Funny

    ....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.
    1. Re:im skeptical... by gmack · · Score: 2

      Someone who hates everything else even more?

      It has the advantage that it does backwards compatibility well with advance notice when a feature is about to disappear This means that if I need to upgrade my PHP application, I am sure to have a version that supports both the new interfaces and the old deprecated interfaces and more importantly it means that if I have a number of different apps that I need installed, I am not likely to need to move them each into their own VM. Python as an example of everything I hate doesn't even try. Their "fix" is to install a local copy of python with the app which is great until something needs a security update and now someone must upgrade each app's environment individually.

  3. PHP is fine by bsdasym · · Score: 5, Insightful

    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.

    1. Re:PHP is fine by John+Bokma · · Score: 3, Interesting

      I think the problem a lot of programmers have with PHP is that it originally was written by very inexperienced programmer(s) and it still (?) shows.

    2. Re:PHP is fine by Bengie · · Score: 5, Funny

      Not the languages fault, ehh? sounds like a lawyer cop-out for bad design. The owner's manual clearly states that if you put on your turn signal while slowing down, the radio station is at 98.6fm and the temperature outside is between 42f and 50f, the car will deploy the air bags. Clearly the user is at fault for not being ready for airbag deployment.

    3. Re:PHP is fine by Zarjazz · · Score: 3

      Blaming the language for bad code is asinine.

      It's not asinine but it is probably overly harsh.

      PHP is popular because it's easy for beginners to learn, easy to get stuff done quickly & simply, and easy for programmers familiar in C & C++ to start web development without having to grok a completely unfamiliar language.

      PHP is bad because it's easy for everyone using it to write insecure code.

    4. Re:PHP is fine by greg1104 · · Score: 5, Funny

      The problem with the PHP community is that it's filled with the kind of people who feel it's good idea to work on PHP.

    5. Re:PHP is fine by bad-badtz-maru · · Score: 2

      If you write a good foundation of libraries and classes you'll need a hack like APC to get any decent execution speed. It also sucks at memory utilization. Everyone likes to link to that "fractal of bad design" article, but it's pretty much just a bunch of whining. Here's a real article that just plain hurts, it has to do with PHP's memory allocation: https://nikic.github.io/2011/1...

    6. Re:PHP is fine by Bogtha · · Score: 4, Insightful

      Blaming the language for bad code is asinine.

      This is bullshit. A shitty language promote shitty code. Aside from the whole taking pride in your work and other "soft" effects, in PHP's case, there are several big, concrete instances of this happening.

      For example, older versions of PHP were obviously designed without any clear understanding of how a web request operates. So, for example, you'd have SQL escaping happening in the input layer rather than at the database layer. Nobody who understands what they are doing would design something to work that way. But the core PHP devs totally fucked up in the beginning. They have since started to pull this crap out of PHP, but take a look around. Big, widely-used PHP packages like CodeIgniter have replicated this topsy-turvy design fuckup even in recent versions. That's no coincidence - that's inherited from PHP's design flaws. The blind led the blind into hell, and this crap permeates the PHP developer community as a result.

      Likewise with the cavalier attitudes towards correctness. Error handling, character encoding, testing, release management, things like that. Where PHP fucks up, the community is sure to follow. The low quality of PHP has a direct negative effect on the code its fans write.

      I'm fed up with the equivocation PHP fans trot out whenever any criticism heads their way. Yes, the quality of a language really does have an effect on the quality of the code you write with it. This is plain for anybody to see, and if you don't see the difference in quality, then you should seriously question your competence.

      --
      Bogtha Bogtha Bogtha
    7. Re:PHP is fine by dave420 · · Score: 2

      You seem to be confusing PHP with Wordpress. Don't do that. It makes you look entirely idiotic.

  4. Re:Too little too late by prod-you · · Score: 2

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

  5. Sometimes bad tools are just bad. by Anonymous Coward · · Score: 2, Insightful

    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.

  6. Re:Yes. by whh3 · · Score: 4, Insightful

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

    If your function is hundreds of lines long just because you didn't use a goto, you're still doing it wrong.

    --
    remove nospam. to email!
  7. Never understood the PHP hate by MBGMorden · · Score: 2, Insightful

    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
  8. Couch programmers bashing again. by kennycoder · · Score: 5, Insightful

    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.
  9. I miss Slashdot / get off my lawn by Anonymous Coward · · Score: 2, Informative

    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.

  10. Re:Install by ericlondaits · · Score: 2

    Just install one of the many many WAMP packages (WAMP = Windows + Apache + MySQL + PHP). Typically you just run a setup executable and get a ready to use installation of Apache with PHP and a MySQL server, which normally includes phpMyAdmin and some other helpful stuff.

    --
    As a Slashdot discussion grows longer, the probability of an analogy involving cars approaches one.
  11. No Static Typing by aberglas · · Score: 3, Interesting

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

  12. Re:Not By Choice by Bing+Tsher+E · · Score: 2

    Javascript is what makes pages load on peoples' browsers in seconds instead of milliseconds. It can turn a relatively recent computer or tablet into a slug.

    Keep your 'code' outta the marked up text that I'm trying to read. Nobody cares that you think you're a 'web developer' because you can slow down a stream of text that your 'users' are trying to fricking read.

  13. I CAN tell you. Autoglobals, for 1. Much better by raymorris · · Score: 2

    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.