Skip to content

Instantly share code, notes, and snippets.

@eddieajau
Created May 4, 2012 23:29
Show Gist options
  • Save eddieajau/2598367 to your computer and use it in GitHub Desktop.
Save eddieajau/2598367 to your computer and use it in GitHub Desktop.
PSR-1,2 Combined variant

PSR-1 PHP Code Style Standard

Version: 1 2012-05-??

This standard comprises the code style requirements for interoperability (Section 1) and the best practices guidelines (Section 2) for PHP projects.

O Definitions

studly-caps refers to a naming convention where all 'words' in the name are conactenated and have only the first letter in uppercase followed by lower case letters (for example "StudlyCaps").

camel-caps refers to a naming convention is like studly-caps except that the first letter in the word is lower case (for example "camelCaps").

Vendor is a generic term that refers to the individual or organisation who produces the code.

Class is generally considered synonymous with interface and traits unless specified otherwise (or is not applicable). Where requirements or guidelines are interfaces and traits are not specifically mentioned, those for classes will be assumed to apply.

1 Requirements

This section of the standard comprises what should be considered the mandatory styling elements that are required to ensure a high level of interoperability between shared PHP code.

1.1 PHP Tags

Long <?php ?> and short-echo <?= ?> tags are permitted for defining PHP codeblocks.

1.2 Character Encoding

PHP files must be stored using UTF-8 (no BOM) character encoding.

1.3 Namespace and Class Names

For code intended to be used with PHP 5.3 or later, all namespaces and classes are to be named with PSR-0 in mind. In doing so, each class is in a file by itself, and is in a namespace of at least one level (a top-level vendor name).

Class names are to be declared in studly-caps.

For code written to support earlier versions of PHP, the pseudo-namespacing convention of Vendor_ prefixes on class names should be considered.

For example:

<?php
// PHP 5.3 or later.

// Class name in StudlyCaps and vendor, and namespaced.

namespace Vendor\Model;

class Foo
{
}
<?php
// Earlier than PHP 5.2.

// Class name in studly-caps and vendor, with vendor prefix.
class Vendor_ModelFoo
{
}

1.4 Class Constants

Class constants must be declared class in upper case with underscore separators if required. For example:

<?php
class PhpFigPsr1
{
    const VERSION;
    const DATE_APPROVED;
}

1.5 Class Methods

Class method names are to be declared in camel-caps. For example:

<?php
class PhpFigPsr1
{
    public function isCompliant()
    {
    }
}

2 Best Practice Guidelines

This section comprises a collection of the best practices used within the PHP community in order to provide a consistent stylistic approach to coding PHP libraries and projects. The intent of this guide is to reduce cognitive friction when scanning code from different vendors.

This section is to be considered non-mandatory, but does form the common practice observed in most of the PHP community. It is understood that variations will arise and in such cases, vendors should note clearly in their own style guides where they deviate or vary from this section.

2.1 Files

The Unix LF (linefeed) line ending should be used in all PHP files.

Where a files only contains PHP code, omit the closing ?> tag.

End each file with a single blank line.

2.3 Lines

There is no hard limit on line length. A soft limit of 120 characters is recommended. Automated style checkers should output a warning (or an error at the discretion of the vendor) when lines exceed the nominated soft limit.

Trailing spaces should be stripped from the end of lines (most programming editors have an option to do this automatically on save).

Blank lines should be added to improve readability and to indicate related blocks of code.

Use at most one statement per line.

2.2 Indenting

Use four (4) real spaces for indenting code.

2.3 Namespace and use

Place one blank line after the namespace declaration.

All use declarations go after the namespace declaration. There is one use keyword per declaration.

Place one blank line after the use block.

For example:

namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

// ... additional PHP code ...

2.4 Classes

2.4.1 Class Definition

Declare extends and implements keywords on the same line as the class name.

The opening and closing braces for the class go on their own line.

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements InterfaceName
{
    // constants, properties, methods
}

Lists of implements may be split across multiple lines, where each subsequent line is indented once. List only one interface per line.

<?php
namespace Vendor\Package;

use FooClass;
use BarClass as Bar;
use OtherVendor\OtherPackage\BazClass;

class ClassName extends ParentClass implements
    InterfaceName,
    AnotherInterfaceName,
    YetAnotherInterface,
    InterfaceInterface
{
    // constants, properties, methods
}

2.4.2 Properties

Declare visibility on all properties. Do not use var to declare a property. Declare only one property per statement.

A property declaration looks like the following.

<?php
namespace Vendor\Package;

class ClassName
{
    public $foo = null;
}

2.4.3 Methods

Declare visibility on all methods.

Declare methods with no space after the method name. The opening and closing braces go on their own line. There is no space after the opening parenthesis, and there is no space before the closing parenthesis.

A method declaration looks like the following. Note the placement of parentheses, commas, spaces, and braces:

<?php
namespace Vendor\Package;

class ClassName
{
    public function fooBarBaz($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}

2.4.4 Method Arguments

Method arguments with default values always go at the end of the argument list.

<?php
namespace Vendor\Package;

class ClassName
{
    public function foo($arg1, &$arg2, $arg3 = [])
    {
        // method body
    }
}

Argument lists may be split across subsequent indented lines; list only one argument per line. When the argument list is split across multiple lines, the closing parenthesis and opening brace are placed together on their own line.

<?php
namespace Vendor\Package;

class ClassName
{
    public function aVeryLongMethodName(
        ClassTypeHint $arg1,
        &$arg2,
        array $arg3 = []
    ) {
        // method body
    }
}

2.4.5 Qualifiers

When present, the abstract and final declarations precede the visibility declaration.

When present, the static declaration comes after the visibility declaration.

<?php
namespace Vendor\Package;

class ClassName
{
    protected static $foo;

    abstract protected function zim();

    final public static function bar()
    {
        // method body
    }
}

2.3 Control Structures

The general style rules for control structures are as follows:

  • one space after the control structure keyword
  • no space after the opening parenthesis
  • no space before the closing parenthesis
  • one space between the closing parenthesis and the opening brace
  • structure body indented once
  • closing brace on the line after the body, outdented once from the body

Always use braces to enclose the body of each structure. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body.

2.3.1 if-elseif-else

An if structure looks like the following. Note the placement of parentheses, spaces, and braces; and that else and elseif are on the same line as the closing brace from the earlier body.

<?php
if ($expr1) {
    // if body
} elseif ($expr2) {
    // elseif body
} else {
    // else body;
}

N.b.: There appears to be no consistency between projects, and often not even within the same project, on the use of else if vs elseif. This guide encourages the use of elseif so that all control structures look like single words.

2.3.2 switch and case

A switch structure looks like the following. Note the placement of parentheses, spaces, and braces; the indent levels for case and break; and the presence of a // no break comment when a break is intentionally omitted.

<?php
switch ($expr) {
    case 1:
        echo 'First case';
        break;
    case 2:
        echo 'Second case';
        // no break
    default:
        echo 'Default case';
        break;
}

2.3.3 while and do-while

A while statement looks like the following. Note the placement of parentheses, spaces, and braces.

<?php
while ($expr) {
    // structure body
}

Similarly, a do while statement looks like the following. Note the placement of parentheses, spaces, and braces.

<?php
do {
    // structure body;
} while ($expr);

2.3.4 for

A for statement looks like the following. Note the placement of parentheses, spaces, and braces.

<?php
for ($i = 0; $i < 10; $i++) {
    // for body
}

2.3.5 foreach

A foreach statement looks like the following. Note the placement of parentheses, spaces, and braces.

<?php
foreach ($iterable as $key => $value) {
    // foreach body
}

try-catch

A try catch block looks like the following. Note the placement of parentheses, spaces, and braces.

<?php
try {
    // try body
} catch (FirstExceptionType $e) {
    // catch body
} catch (OtherExceptionType $e) {
    // catch body
}

2.4 In-Code Documentation

All PHP files should include a DocBlock header.

All classes should include a DocBlock for the class definition.

All class contants, properties and methods should include a DocBlock to explain their purpose.

All functions should include a DocBlock to explain their purpose.

@kinncj
Copy link

kinncj commented May 5, 2012

namespace Vendor\Model;

class VendorModelFoo
{
}

you want to say

namespace Vendor\Model;

class Foo
{
}

?

AND

class Vendor_ModelFoo
{
}
U want to say

class Vendor_Model_Foo
{
}

?

@eddieajau
Copy link
Author

Thanks. Fixed the first case. For the second it depends on the autoloader rules. For the second case, the "note" only said to prefix with "Vendor_". It didn't say what followed needed to also be underscore separated.

@kinncj
Copy link

kinncj commented May 5, 2012

Yeah, but i don't think that u will have something like
Vendor/ModelFoo.php
so, looking at PSR0 you will find what i said...
When i see Vendor_ModelFoo i expect Vendor/ModelFoo.php...
So i think that the correct way is Vendor_Model_Foo for Vendor/Model/Foo.php right? or not?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment