Good Practices for PHP

Continuously extended blogpost containing good practices for the PHP scripting language

Published:

Content

Introduction

Lately, many articles appeared in the PHP community, discussing the pros and cons of the scripting language. I recommend reading the two articles “PHP: a fractal of bad design” and “PHP Sucks! But I Like It!”.

Whether one likes PHP or not: In my opinion, the following two facts cannot be ignored:

  1. PHP is currently the language with the most free hosting providers available.
  2. PHP has a market share of 78.1% (as of October 2012) of the server-side programming language for websites.

For the second reason alone, it does make sense to deal with PHP, whether one likes it or not. Unfortunately, the World Wide Web (WWW) is full of PHP articles, which were apparently written by people who have little experience with computer programming. Such articles spread outdated information, contain wrong and unsafe source code and even propagate “Bad Practices” sometimes. This leads, among other things, to the point, that PHP programmers are often ridiculed as “script kiddies”.

Nevertheless, there is hope: In recent years, PHP changed significantly (one need only to read the changelog of version 5.3 and version 5.4). Furthermore, the community has changed dramatically for the better.

This article serves me to collect resources on PHP: Good Practices. Since I don’t want to repeat information that is available elsewhere, I use this blogpost to aggregate that ressources and to post own suggestions that are not covered in these ressources.

Resources

  • PHP: The Right Way > PHP: The Right Way is an easy-to-read, quick reference for PHP best practices, accepted coding standards, and links to authoritative tutorials around the Web.
  • PHP-FIG - PHP Framework Interop Group > The idea behind the group is for project representatives to talk about the commonalities between our projects and find ways we can work together.
  • 30+ PHP Best Practices for Beginners > PHP is the most widely-used language for programming on the web. Here are thirty best practices for beginners wanting to gain a firmer grasp of the fundamentals.
  • Why You’re a Bad PHP Programmer > We all have our bad habits. In this article, we’ll go over a list of bad practices that are worth examining, reevaluating, and correcting immediately.
  • The PHP Benchmark > PHPBench.com was constructed as a way to open people’s eyes to the fact that not every PHP code snippet will run at the same speed.

Make sure that you also read The MicroPHP Manifesto, especially the original blogpost.

Development Environment

Mandatory

  • Use an Integrated Development Environment (IDE). To the people who still develop with text editors: Come on, this aren’t the 80’s. Anyone who claims that he is more productive with a text editor than with an IDE is a lier. I recommend one of the following IDEs for PHP development:

    • Oracle NetBeans IDE

      • Pros

        • Open-Source Software (OOS)
        • Platform independent (runs on Windows, Mac OS X, Linux)
        • Integration of Version Controls Systems (VCS) (Subversion, Git)
        • Plugin architecture
        • Integration of PHPUnit
        • Integration of PHP_CodeSniffer, PHP Mess Detector (PHPMD), PHP_Depend, phpcpd and phpdcd via plugins
        • Integration of full-stack frameworks (Zend Framework, Symfony, Symfony2)
        • Integration of template engines (Smarty, Twig)
      • Cons

        • Performance (consumes a lot of resources, e.g. central processing unit and main memory)
    • JetBrains PhpStorm

      • Pros

        • Performance (less resource hungry)
        • Platform independent (runs on Windows, Mac OS X, Linux)
        • Integration of Version Controls Systems (VCS) (Subversion, Git, Mercurial)
        • Plugin architecture
        • Integration of PHP_CodeSniffer and PHPUnit
        • Integration of full-stack frameworks (Symfony2, Yii)
      • Cons

        • Closed-Source Software
        • Costs money

Optional

  • Use a proper monospaced ClearType font (e.g. Consolas) in the IDE of your choice.

    You think that this is a ridiculous point? Change the default font in NetBeans IDE from Monospaced (size 13) to Consolas (size 15) and you’ll see why I mention this!

Forbidden

  • Do not use a text editor as a replacement for an IDE.

Test

Mandatory

  • Use the unit test framework PHPUnit for dynamic software test procedures (e.g. component tests (unit tests) and integration tests).

    • Use two different XML configuration files (you can start with PHPUnit Boilerplate):

      • phpunit.xml in a development environment
      • phpunit.xml.dist in a Continuous Integration (CI) environment

Coding Style

General

Mandatory

  • Follow the PSR-0 requirements for autoloader interoperability.
  • Follow the PSR-1 basic coding style guide.
  • Follow the PSR-2 coding style guide.
  • Use the style checker PHP_CodeSniffer with the standard psr2 to check the PHP source code against the PSR-2 coding style guide.

    phpcs --standard=psr2 <file>
    
  • Use the PHP Coding Standards Fixer to automatically modify the source code syntax so that it conforms with the PSR-2 coding style guide.

Optional

  • Create your own coding style on top of the PSR-2 coding style guide.

Forbidden

  • Create your own coding style that does not follow the PSR-2 coding style guide.

Classes and class members (constants, attributes and methods)

Visibility

  • Try to avoid protected attributes and methods. Only use them in a class which is extended by one or more other classes.
  • Use package-private visibility whenever possible, e.g.:
    • to create “pseudo inner classes”
    • to provide an Application Programming Interface (API) through a Service Layer

Methods

  • A method should not have more than three arguments.
  • A method should solve one task.
  • Blocks within if- else-, while- and similar structures should not be longer than one line.
  • Do not use call-time pass-by-reference.

    Reason: > [.] as of PHP 5.4.0, call-time pass-by-reference was removed, so using it will raise a fatal error.

Note: These rules are hard to follow, but improve the readability of the source code a lot. The rules above can be fulfilled by using Refactoring, e.g. Extract Method.

Exceptions

  • Consider the Tester-Doer and TryParse patterns for members that may throw exceptions in common scenarios to avoid performance problems related to exceptions. (cf. Exceptions and Performance)

Comparison of constants and literals

  • Use strict comparison whenever possible: Always use the identity operator (===) and not the equals operator (==). Always use keywords, when comparing with true, false or null. Always use the expected return value of a function or method.

    Reason: Type Juggling.

    if ($foo)           // Bad, avoid truthy comparisons
    if (true == $foo)   // Bad, avoid truthy comparisons
    if (true === $foo)  // Good
    if (!$bar)          // Bad, avoid falsy comparisons
    if (true != $bar)   // Bad, avoid falsy comparisons
    if (true !== $bar)  // Better
    if (false === $bar) // Good
    if (null !== $bar)  // Good
    
  • Put keywords, constants and literals on the left side of the comparison expression. Reason: An accidental assignment via = inevitably leads to a compiler error.

    if ($foo !== true)           // Bad
    if (true !== $foo)           // Good
    if (self::instance === null) // Bad
    if (null === self::instance) // Good
    if ("\n" === \PHP_EOL)       // OK
    if (\PHP_EOL === "\n")       // Good
    

Operators

  • Use the prefix operator ++$i and not the postfix operator $i++ to increment an integer whenever possible.
  • Use the prefix operator --$i and not the postfix $i-- to decrement an integer whenever possible.

    Reason: The prefix operation is slightly faster than the postfix operation. But even more important is that these operations are used consistant in the source code.

Software Quality

I recommend reading the book S. Bergmann, S. Priebsch. Softwarequalität in PHP Projekten, München: Hanser, 2010.

Principles

Implementation Patterns

I recommend reading the following books:

Design Patterns

I recommend reading the following books:

Architecture Patterns

I recommend reading the book M. Fowler. Patterns of Enterprise Architecture, Boston: Addison-Wesley, 2002..