Giter Site home page Giter Site logo

php-coding-standards's Introduction

PHP Coding Standards

PSR-1/2/4/5/12 are a solid foundation, but are not an entire coding style by themselves.

This guide goes well-beyond brace placement and tabs vs. spaces to cover topics such as docblock annotations, ternary operations and which variation of English to use. It aims for thoroughness and pedanticism over hoping that we can all get along.

  • PSR-1 — Basic Coding Style
  • PSR-2 — Coding Style Guide
  • PSR-4 — Autoloading Patterns
  • PSR-5 — Documentation Block Patterns
  • PSR-12 — Extended Coding Style
  • Symfony — Additional Standards.

Enforced by Code

I have reduced these written-word guidelines to only specify what I cannot enforce using existing linters. Here are the linter rules which should be used by PHP Code Sniffer and PHP CS Fixer.

These can (and should, often) be run to fix coding style errors.

make lint

Guidelines

Naming Things

  • Constants are always ALL_CAPS.

  • Abstract classes should be called Abstract{Name}.

  • Interfaces should be called {Name}Interface.

  • Traits should be called {Name}Trait.

  • Namespaces, classes, traits, interfaces, etc., should all prefer singular names.

    MyCode\Mixin\ResponseHandler
    MyCode\Mixin\TableFormatter
    MyCode\Util\DataGenerator
  • There's no hard and fast rule when it comes to the length of a name, so just try and be as concise as possible without affecting clarity too much.

  • According to PSR-4, a class called MyCode should be in a file called MyCode.php.

Constants

  • Global constants are bad.

  • Class constants are good.

  • Enum-like class constants are better.

Strings

  • Single quotes most of the time.

  • sprintf() is the preferred form for injecting variables into strings.

  • For string interpolation (e.g., with HEREDOC), use the {$variable} format. Do NOT use ${variable} or $variable.

  • NOWDOC strings are preferred over HEREDOC strings.

  • Use NOWDOC/HEREDOC for multi-line strings.

Ternary Statements

  • Don't test if the statement is false. That becomes confusing fast.

  • Preferred formatting is:

    $condition
        ? true
        : false;
  • Use ?? when possible.

    return $data[0] ?? null;

Comments

  • Non-documentation comments are strongly encouraged.

  • A general rule of thumb is that if you look at a section of code and think "Wow, I don't want to try and describe that", you need to comment it should refactor it before you forget how it works.

  • C-style comments (/* */) and standard C++ comments (//) are both fine. However, single-line comments should opt for //, while multi-line comments should opt for /* */.

  • For readability, add a single space after // style comments, and an extra space immediately inside both ends of a /* */-style comment.

DocBlocks

  1. Follows the PSR-5 (draft) pattern.

  2. Any short-hand refrences to software licenses should use the SPDX identifier.

  3. Data types (if they are classes) can either be fully-qualified, or can match a valid namespace alias.

    /**
     * [getSomeKindOfData() description]
     * 
     * @param  string           $string [description]
     * @param  SimpleXMLElement $xml    [description]
     * @return [type]                   [description]
     * 
     * @throws [Exception class]
     */
    public static function getSomeKindOfData($string, SimpleXMLElement $xml) {
        // ...
    }
  4. Leveraging return types (PHP 7.0+) is the preferred approach for informing IDEs about which classes we're working with.

    use Symfony\Components\EventDispatcher\EventDispatcher;
    
    public function getDispatcher(): EventDispatcher
    {
        return $this->dispatcher;
    }

Spelling

If there is ever a discrepancy between English-speaking dialects, use U.S. English as a baseline for both spelling and word choice. Grammarist and similar websites can help ensure intended usage.

color (correct)
colour (incorrect)

spelled (correct)
spelt (incorrect)

canceled (correct)
cancelled (incorrect)

labeled (correct)
labelled (incorrect)

math (correct)
maths (incorrect)

apartment (correct)
flat (incorrect)

"Apple is very successful." (correct)
"Apple are very successful." (incorrect)

CLI

  • When writing CLI scripts, don't presume to know where the PHP binary is installed. Use the env binary to pick-up from the local environment.

    #! /usr/bin/env php

PHP_EOL

  • Rather than using \n or \r\n as forced line breaks in your files, use the PHP_EOL constant instead.

  • PHP will use whichever end-of-line character is most appropriate for the platform that it's currently running on.

Blacklisted

Never use the following features of PHP. The world will come to an end if you do.

Miscellaneous

  • No global variables. (ಠ_ಠ)

  • Code must not produce any warnings or errors when PHP's error reporting level is set to error_reporting(-1). (Source)

  • You are encouraged to give increment/decrement operators (++ and --) a line of their own (with the exception of for loops).

    $foo[$i++] = $j; // Discouraged: relies on $i being incremented after the expression is evaluated
    $foo[--$j] = $i; // Discouraged: relies on $j being decremented before the expression is evaluated
    
    $foo[$i] = $j;
    $i++;            // Encouraged: obvious when $i is incremented
    
    $j--;
    $foo[$j] = $i;   // Encouraged: obvious when $j is decremented

License

My intention is to release all rights to this documentation and make it available under the Public Domain. Unfortunately, in the U.S. it's not quite that cut-and-dry. So, I am dual-licensing this work under CC0 and the Unlicense. You can choose whichever license you would prefer to adhere to.

To the extent possible under law, the AUTHOR has waived all copyright and related or neighboring rights to "PHP Coding Standards". This work is published from: United States.

php-coding-standards's People

Contributors

skyzyx avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

php-coding-standards's Issues

?:

$next = $next ?: function (Request $request, Response $response) {

  •        return $response;
    
  •    };
    

Empty line after indented statement

 $id = Db\Achieve\Projects::factory($container['db'])
 +                    ->select(['id'])
 +                    ->where('uuid', $args['project'])
 +                    ->value('id');
 +                $updates['project'] = $id;

Indenting sub statements

As a pattern, I've been indenting -> child statements 4-spaces from the left edge of the parent part of the statement.

$isSaved = Db\Achieve\Areas::factory($container['db'])
->insert(
// ...
);

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.