PHPackages                             remy-theroux/php-convention - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. remy-theroux/php-convention

ActivePhpcodesniffer-standard[Utility &amp; Helpers](/categories/utility)

remy-theroux/php-convention
===========================

Set of php conventions for modern php applications

0.2(6y ago)041[1 PRs](https://github.com/remy-theroux/php-convention/pulls)MITPHPPHP ^7.3

Since Oct 25Pushed 6y ago1 watchersCompare

[ Source](https://github.com/remy-theroux/php-convention)[ Packagist](https://packagist.org/packages/remy-theroux/php-convention)[ RSS](/packages/remy-theroux-php-convention/feed)WikiDiscussions master Synced today

READMEChangelog (2)Dependencies (2)Versions (3)Used By (0)

ModernPhp Style Guide
=====================

[](#modernphp-style-guide)

Usage
-----

[](#usage)

vendor/bin/phpcs --standard=ModernPhp your\_path

### Troubleshooting

[](#troubleshooting)

Standard must be auto installed via a composer plugin in the package dealerdirect/phpcodesniffer-composer-installer

If you have this error `'PHP_CodeSniffer_Exception' with message 'Referenced sniff "ModernPhp" does not exist'`

Add manually standard to your installed path: `./vendor/bin/phpcs --config-set installed_paths $PWD/vendor/remy-theroux/php-convention`

Table of Contents
------------------------------------------------

[](#table-of-contents)

1. [IDE Integration](#installation)
2. [Files](#files)
3. [Lines](#lines)
4. [Keywords](#keywords)
5. [Comments](#comments)
6. [Naming](#naming)
7. [Variables](#variables)
8. [Constants](#constants)
9. [Type casting](#type-casting)
10. [Namespaces and use declarations](#namespaces-use)
11. [String](#strings)
12. [Arrays](#arrays)
13. [Classes, Properties, and Methods](#classes)
14. [Interfaces, Traits](#interfaces)
15. [Function and Method Calls](#function-method-calls)
16. [Control Structures](#control-structures)
17. [Closures](#closures)
18. [Best practices](#best-practices)

Files
--------------------------------------

[](#files)

- Use only `UTF-8 without BOM`.
- Use only the Unix LF (linefeed) line ending.
- All PHP files must end with a single blank line.
- Use the long `` tags for non-views scripts.

```
` tags for view scripts.

```

```

- The closing `?>` tag must be omitted from files containing only PHP.
- Limit on line length limit must be `200 characters`.
- File must contain only one statement of namespace.
- Code must use `4 spaces` for indenting, not tabs.

Lines
--------------------------------------

[](#lines)

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

```
// nah
function foo()
{
    $foo = 'test';
    $foo = strtoupper($foo);
    return $foo;
}

// good
function bar()
{
    $foo = 'test';
    $foo = strtoupper($foo);

    return $foo;
}
```

- There must not be more than one statement per line.

```
// bad
$foo = substr(strtoupper('test'), 0, 1);

// good
$foo = 'test';
$foo = strtoupper($foo);
$foo = substr($foo, 0, 1);
```

Keywords
--------------------------------------------

[](#keywords)

- All PHP keywords must be in lower case (Eg: `true`, `false`, `null`, etc.)

Namespaces and use declarations
-------------------------------------------------------------------------

[](#namespaces-and-use-declarations)

- Namespaces names must be delcared in `UpperCamelCase`.

```
// bad
namespace Vendor\fooBar;

// bad
namespace Vendor\foo_bar;

// good
namespace Vendor\FooBar;
```

- Namespaces declaration never begin by a backslash `Vendor\Space\Space`.
- There must be one blank line before and after the `namepsace` declaration.
- There must be one blank line after the block of `use` declaration.
- `use` declaration must not separated by comma.
- `use` block declarations must be grouped by package:

```
// bad
use Foo\Bar,
    Qux\Quux,
    Foo\Baz;

// bad
use Foo\Bar;
use Qux\Quux;
use Foo\Baz;

// good
use Foo\Bar;
use Foo\Baz;
use Qux\Quux;
use Qux\Corge\Grault;
```

- `use` alias declaration should be composed with sub-namespaces names.

```
// bad
use Foo\Bar as Baz;

// bad
use Baz\Qux\Quux as BQQ;

// good
use Foo\Bar as FooBar;

// good
use Baz\Qux\Quux as BazQuxQuux;
```

Comments
--------------------------------------------

[](#comments)

### In-line code comments

[](#in-line-code-comments)

- Comments should be on a separate line immediately before the code line or block they reference.

```
// bad
$foo = 'bar'; // Bar in foo

// good
// Foo assignment for example
$foo = 'bar';

// good
// Foo assignment
// for example
$foo = 'bar';
```

### Block code comments

[](#block-code-comments)

- You must add PHPDoc blocks for all classes, methods, and functions, but you can omit the `@return` tag if the method does not return anything.

```
/**
 * Foo
 *
 */
class Foo
{
    /**
     * The description of bar
     *
     * @param string $baz The baz
     *
     * @return string The return of bar
     */
    public function bar($baz)
    {
        // Returned value
        return 'Do something...';
    }
}
```

- You must add PHPDoc blocks for all variable references.

```
/** @var Bar\Baz $foo Baz object */
$foo = $bar->baz();

```

```
/**
 * Foo
 *
 */
class Foo
{
    /** @var string $bar It's bar! */
    public $bar = '';
}
```

- You must not use full qualified class name in PHPDoc blocks. This means you have to declare the class name with a use declaration even if she is not referenced elsewhere from the PHPBlock.

```
// Bad
namespace Vendor\Bar\Baz;

/**
 * Foo
 *
 */
class Foo
{
    /** @var \Other\MyClass $myClass */
    protected $myClass;

    /**
     * @return \Other\MyClass
     */
    public function getMyClass()
    {
      return $this->myClass;
    }
}
```

```
// Good
namespace Vendor\Bar\Baz;

use Other\MyClass;

/**
 * Foo
 *
 */
class Foo
{
    /** @var MyClass $myClass */
    protected $myClass;

    /**
     * @return MyClass
     */
    public function getMyClass()
    {
      return $this->myClass;
    }
}
```

- `@todo` and `@fixme` must be used in PHPDoc blocks like annotations.

```
/** @todo Think to check value */
$foo = 'bar';

/** @fixme Change qux to quux */
$baz = 'qux';
```

### Qualify objects you use

[](#qualify-objects-you-use)

- you should add `@var` tag when you get object from abstract method

```
// bad
$logger = $this->getServiceLocator()->get('logger');

// bad
$this->getServiceLocator()->get('AwesomeFactory')->createAwesomeness();

// good
/** @var LoggerInterface $logger */
$logger = $this->getServiceLocator()->get('logger');

// good
/** @var AwesomeFactory $awesomeFactory */
$awesomeFactory = $this->getServiceLocator()->get('AwesomeFactory');
$awesomeFactory->createAwesomeness()
```

- you shouldn't add `@var` tag when you get object from explicit method

```
// bad
/**
 * Class AwesomeFactory
 */
class AwesomeFactory
{
    /**
     * @return Awesome
     */
     public function createAwesomeness()
     {
         return Awesome();
     }
}
$awesomeFactory = new AwesomeFactory();
/** @var Awesome $awesome */
$awesome = $awesomeFactory->createAwesomeness();

// good
/**
 * Class AwesomeFactory
 */
class AwesomeFactory
{
    /**
     * @return Awesome
     */
     public function createAwesomeness()
     {
         return Awesome();
     }
}
$awesomeFactory = new AwesomeFactory();
$awesome        = $awesomeFactory->createAwesomeness();
```

Naming
----------------------------------------

[](#naming)

- Clarity over brevity in variable, method and class names

```
// bad
$o = new Object();

// bad
class A
{
}

// bad
public function doIt()
{
}

// good
$object = new Object();

// good
class Substracter
{
}

// good
public function associateChannelToOperator()
{
}
```

- `Boolean` variable names should be either an adjective or a past participle form. Associated getter method should begin with `is` or `has`.

```
// bad
$enablePlugin = true;

// bad
public function getEnablePlugin() {}

// bad
public function getPluginEnabled() {}

// good
$pluginEnabled = true;

// good
$visible = true;

// good
public function isPluginEnabled() {}

// good
public function isVisible() {}
```

- `DateTime` variable names should be a past participle form ending with `At`.

```
// bad
$dateUpdate = new \DateTime;

// bad
$endDate = new \DateTime;

// good
$updatedAt = new \DateTime;

// good
$lastLoggedAt = new \DateTime;
```

Variables
----------------------------------------------

[](#variables)

### User variables

[](#user-variables)

- Variables should be in `lowerCamelCase`.

```
// bad
$_foo='';

// bad
$foo_bar = '';

// bad
$fooBar='';

// good
$fooBar∙=∙'';
```

- You must set off operators with spaces.

```
// bad
$foo = (5+6)/5;

// good
$foo∙=∙(5∙+∙6)∙/∙5;
```

- You must conserve a great alignment.

```
// bad
$foo = 'Ba';
$foo .= 'r';
$quux = 'Qu';
$quux .= 'x';

// good
$foo   = 'Ba';
$foo  .= 'r';
$quux  = 'Qu';
$quux .= 'x';
```

```
// bad
$fooBarBazQux->bar()->
    baz()->qux();

// good
$fooBarBazQux
∙∙∙∙->bar()
∙∙∙∙->baz()
∙∙∙∙->qux();
```

### Global variables

[](#global-variables)

- You must used `$_POST`, `$_GET` and `$_COOKIE` instead of `$_REQUEST`. If you use a framework, use `Request` component.

Strings
------------------------------------------

[](#strings)

- A string must be enclosed in single quotes `'hello'`.
- A concatenated string must use single quotes `'foo' . $bar`
- A concatenated string must use spaces around points `'foo' . $bar`
- A string declaration in multiline must be aligned

```
$foo = 'Bar'
      .'Baz'
      .'Qux';
```

- A string must not concatenate with functions or methods

```
// bad
$foo = ucfisrt('bar') . ' baz';

// good
$foo = ucfirst('bar');
$foo = $foo . ' baz';

// very good
$foo  = ucfirst('bar');
$foo .= ' baz';
```

Constants
----------------------------------------------

[](#constants)

### Class constants

[](#class-constants)

- Constants must be in `UPPER_SNAKE_CASE`.

```
// bad
const MAXSIZE=5;

// bad
const max_size∙=∙4;

// good
const MAX_SIZE∙=∙5;
```

- You must set assignment operator with spaces.

```
// bad
const MAX_SIZE=5;

// good
const MAX_SIZE∙=∙5;
```

- You must conserve a great alignment.

```
// bad
const FOO∙∙=∙'Ba';
const FOO∙∙=∙'r';
const QUUX∙=∙'Qu';
const QUUX∙=∙'x';

// good
const FOO∙∙=∙'Ba';
const FOO∙∙=∙'r';
const QUUX∙=∙'Qu';
const QUUX∙=∙'x';
```

Type casting
----------------------------------------------------

[](#type-casting)

- You must use `(int) $foo` instead of `intval($foo)`.
- You must use `(bool) $foo` instead of `boolval($foo)`.
- You must use `(float) $foo` instead of `floatval($foo)`.
- You must use `(string) $foo` instead of `strval($foo)`.

```
// bad
$foo∙=∙(string)$bar;

// good
$foo∙=∙(string)∙$bar;
```

Arrays
----------------------------------------

[](#arrays)

- You must use `[]` notation instead of `array()`.
- Arrays with few data must be declared like this:

```
$foo∙=∙['Bar',∙'Baz',∙'Qux'];
```

- Arrays with lots of data must be declared like this:

```
$foo = [
∙∙∙∙'bar'∙∙=>∙'abc',
∙∙∙∙'baz'∙∙=>∙123,
∙∙∙∙'qux'∙∙=>∙true,
∙∙∙∙'quux'∙=>∙[
∙∙∙∙∙∙∙∙'corge'∙∙=>∙[],
∙∙∙∙∙∙∙∙'grault'∙=>∙123.456,
∙∙∙∙],
];
```

- For the arrays with lots of data, lines must be terminated by a comma. (Easy to copy/paste)

Classes, Properties, and Methods
-------------------------------------------------------------------

[](#classes-properties-and-methods)

### Classes

[](#classes)

- The `extends` and `implements` keywords should be declared on the same line as the class name.
- The opening brace for the class must go on its own line; the closing brace for the class must go on the next line after the body.

```
