Follow Slashdot blog updates by subscribing to our blog RSS feed

 



Forgot your password?
typodupeerror
×
Books PHP Programming Book Reviews

Modern PHP: New Features and Good Practices 182

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.
This discussion has been archived. No new comments can be posted.

Modern PHP: New Features and Good Practices

Comments Filter:
  • by Anonymous Coward

    Best practice for PHP: don't use PHP.

  • hah (Score:1, Insightful)

    by Anonymous Coward

    The best practice for using PHP: don't use it at all!

  • by account_deleted ( 4530225 ) on Monday March 23, 2015 @02:45PM (#49322821)
    Comment removed based on user account deletion
    • by gmack ( 197796 )

      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 everythin

    • by drolli ( 522659 )

      In my experience people who were too lazy to learn perl in the mid 90s and who are not experienced in Java.

  • PHP is fine (Score:5, Insightful)

    by bsdasym ( 829112 ) on Monday March 23, 2015 @02:48PM (#49322839)
    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.
    • Re: (Score:1, Troll)

      by pegr ( 46683 )

      PHP is inherently insecure. You can't have a web platform language with constant patches. One day your fine, the next, rooted. Stay away.

      • by Anonymous Coward

        How the heck is the parent "trolling"?

        That comment is completely true!

        Go check out the PHP changelogs. Some of the bugs being fixed in the 20th or even 30th or more patch release of the various stable releases are unbelievable.

        Clearly there is a quality issue at play when the relatively recent 5.4 version has had 39 patch releases, and the newer 5.5 version has already had 23.

        • by Anonymous Coward

          write better code or learn how to secure your site/server... preferably both.

          i have 5 year old code running on a nearly-as-old version of php and mysql.. no security issues of any kind... on the same server is a couple ancient joomla (yuk) and wordpress installs.. same deal.. the server is secure, the sites are as well despite their obsolete software, and have a few nifty home-grown security measures in place, even the known exploits in both of those very hacker-friendly applications are totally unexploita

    • Re:PHP is fine (Score:4, Interesting)

      by John Bokma ( 834313 ) on Monday March 23, 2015 @02:54PM (#49322889) Homepage
      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.
      • Re: (Score:2, Interesting)

        by ArcadeMan ( 2766669 )

        You clearly never had to use ExpressionEngine. If you think PHP was written by very inexperienced programmers, you're in for the shock of your life.

        ExpressionEngine has something called "Global variables" which are in fact CONSTANTS. And that kind of nonsense is just the tip of the iceberg. Look up their "parsing order", it was created by insane people with no previous programming knowledge.

        • Is that the "general purpose content management system written in object-oriented PHP and using MySQL for data storage"? No, I have no experience with it. I do have (very little) experience with Magento (and like to keep it that way).
          • by pspahn ( 1175617 )

            I have worked extensively with both.

            Expression Engine is just a bunch of ... huh?? It's not bad, but anything other than what they give you can be a pain in the ass. CI in general was always sorta good but shoulda been better.

            Magento has clearly been something that redefined PHP applications. The 1.x branch is going to go down as some of the least maintainable software ever written, but it was bad in a very productive way. 2.x (which you'll probably be seeing in a /. ad in the next few weeks before the co

      • I looked at the first PHP for my employer at the time my summary was a language for those who couldn't hack Perl
      • 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.

        (1) So was Python.

        (2) So does Python.

        Python is only slightly more consistent than PHP, but gets much more bad press than PHP. I always wonder why that is.

    • VHDL.

      Wow. Unlike PHP, Perl, C, C++, C#, Pascal, and ECMAScript, VHDL's got a whole new paradigm.

      the code is elegant and easy to understand as well. Just like every other language

      Maybe I need to learn a new language.

    • by jd142 ( 129673 )
      Oh thank god I'm not the only one. The needle/haystack and whether it is str_foobar or strfoobar drives me nuts. Especially since the phrase is "needle in a haystack" but the function takes haystack, needle. I always want to write find(needle, [in a] haystack). Every language has good and points, and bad coders are bad coders.
      • by Anonymous Coward

        Actually, it's sane is to write

              haystack.find(needle)

        or

            find(haystack, needle)

        for same reasons. Collection first, then operand. If you want "english", use COBOL.

    • by Bengie ( 1121981 ) on Monday March 23, 2015 @03:03PM (#49322959)
      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.
    • by Anonymous Coward

      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 sam

    • Shit man. We had this argument about VB6 back when rock was cool. No one listened then either
    • by Zarjazz ( 36278 )

      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.

    • Re: (Score:2, Informative)

      Only a fanboy makes excuses for why they are too blind to see the many ways it is broken. PHP was designed and developed by a complete fucktard. Let's look at some code ...

      php -a
      echo true . "\n";
      echo false . "\n"; // wat
      echo TRUE . "\n";
      echo FALSE . "\n"; // wat

      Note: The online manual is completely useless:

      * true http://php.net/manual-lookup.p... [php.net]

      * false http://php.net/manual-lookup.p... [php.net]

      * TRUE http://php.net/manual-lookup.p... [php.net]

      * FALSE http://php.net/manual-lookup.p... [php.net]

      More stupid shit PHP does ...

      if(

    • 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... [github.io]

    • Re:PHP is fine (Score:5, Insightful)

      by Bogtha ( 906264 ) on Monday March 23, 2015 @08:17PM (#49324567)

      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.

      • by dave420 ( 699308 )
        Your arguments sound about 8 years old. Seriously. You might want to brush up on your faux rage :)
      • by Xest ( 935314 )

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

        Absolutely and evidence of this is always only a Google search away. Search on how to do something with a database and the results you get are riddled with things like SQL injection

        • by Bogtha ( 906264 )

          Absolutely and evidence of this is always only a Google search away. Search on how to do something with a database and the results you get are riddled with things like SQL injection vulnerabilities, even when the source of the official documentation.

          To follow on from this: Language Community Litmus Test: Database Placeholders [wumpus-cave.net]. An informal survey shows PHP joint bottom, with all but one of the top 5 hits for "PHP database tutorial" promoting insecure methods.

          And, as you mention, the official PHP tuto

    • Bad coders are irrelevant to the fact that PHP is objectively and measurably bad in design and implementation. It started as a toy, and that pedigree still shows.

      Not only is it still the mess of internal inconsistency, braindead weak-typing and promotion, and anemic text support, but there's some amazing -- I mean brilliantly, awe-inspiring, mind-boggling -- idiocy in some of its baked in APIs: LDAPs ldap_list() vs ldap_read() vs ldap_search() all perform the same operation but with different scopes, none o

      • by dave420 ( 699308 )
        Then use an LDAP library like everyone else and stop whining on Slashdot about it. You not understanding how to use a tool which is being effectively used by plenty of other people reflects poorly on you, not them, and not the tool in question.
    • Suppose all guns came without safety catches. I now go and blame this technical oversight for the increase in people with blown-off heads.

      You now claim that blaming the safety-catch-less badly designed guns for the casualties is asinine.

      > It gets the job done quickly and easily,

      So does a gun without a safety catch.

    • Must admit that after complaining about PHP for years, I don't mind it so much now. I think each new PHP release should have the strap-line "PHP x. Less shit than the previous version!", because... it's true!
  • I'm not down with Other People's PHP (OPP), knaw me

  • by MBGMorden ( 803437 ) on Monday March 23, 2015 @04:00PM (#49323321)

    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.

    • weakly-typed variables are a bit aggravating

      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:

      <cfargument
      name="string"
      default="default value"
      displayname="descriptive nam

    • The core is broken. While you have namespaces and patterns to apply inr your code, PHP core functions still don't have namespaces, class, don't even have a pattern in their names/parameters (to not blame the real lack of classes for strings, by example). This only to start. If you want to get deeper: http://me.veekun.com/blog/2012... [veekun.com]
  • by kennycoder ( 788223 ) on Monday March 23, 2015 @04:12PM (#49323393) Homepage
    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.
    • by Xest ( 935314 )

      It's got nothing to do with laziness, at the end of the day the fact remains that PHP has an awful lot more inconsistencies, and has an awful track record on security, stability and functionality.

      I'm skeptical that anyone who claims to have a good depth of experience of PHP but claims it's as fine as anything else really does have the experience they're claiming. As soon as you need to start doing anything serious, like say, making use of threads, PHP's deficiencies rapidly come to the fore when compared to

      • by Xest ( 935314 )

        Hmm. No idea what the fuck just happened to the rest of my post, lucky Slashdot isn't written in PHP or I could blame it for that too :)

        Anyway, basically my point was that it's really not in question that PHP has a number of problems that it's competition simply does not have, those problems are not caused by the programmer, they're caused by the language and it's libraries.

        Yes you can write bad code in .NET, Java, C++ and whatever else, you can also write good code in PHP. None of that is in doubt, but it'

  • by Anonymous Coward

    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.

  • JavaScript has enjoyed a dramatic renaissance as it has been transformed from a browser scripting tool...to a substantial client-side programming language

    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 J

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

      • by dave420 ( 699308 )

        OK, Grandpa. Sorry. We'll get off your lawn now.

        You can install NoScript and have to refresh your pages time and time again any time you want to use them, wasting seconds and many KB in the process. The rest of us will keep using the tools which give us the web we want to use.

        Shouldn't you be napping somewhere?

  • No Static Typing (Score:4, Interesting)

    by aberglas ( 991072 ) on Monday March 23, 2015 @06:27PM (#49324053)

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

    • by rs79 ( 71822 )

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

      You may have won the Internet today. I salute you sir.

      (btw I'm totally stealing this)

    • by dargaud ( 518470 )

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

      Thank god for that.

    • by Jack9 ( 11421 )

      Without any actual evidence, the 40 years of careful research is nothing more than navel gazing. This research has been the equivalent of "don't you think this is true? here's why" which is not how any kind of science is established.

  • Don't.

    :P :P :P

  • 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?

Real Programmers don't eat quiche. They eat Twinkies and Szechwan food.

Working...