FIG

The developed PHP specification, or PSR, is the de facto standard for PHP development. FIG stands for Framework Interoperability Group, founded in 2009 by a handful of open source Framework developers. The aim of the group is to harmonize coding specifications across projects with minimal restrictions, and to avoid the frustration of programmers who develop their own styles. PSR is short for Proposing a Standards Recommendation.

PSR originally had five specifications, which were:

  • Psr-0 (Autoloading Standard) automatically loads the Standard.
  • Basic Coding Standard (PSR-1)
  • Psr-2 (Coding Style Guide) Coding Style wizard.
  • Logger Interface (PSR-3) Log Interface.
  • Improved Autoloading (PSR-4) auto-loaded enhancements to replace THE PSR-0.

Our code specification today is based on the above specification.

1. PHP source files can only be used

2. PHP source files must be UTF-8 encoded files without BOM

BOM (Byte Order Mark) is a Byte Order Mark that appears in the header of a text file and is used in the Unicode encoding standard to identify the format of the file.

3. Indent PHP source files with 4 Spaces

Many editors use Tab for indentation. This can cause space problems.

4. Source file closure tags for pure PHP code? > must be omitted

PHP parsers get a performance boost when interpreting files. And, this can certainly avoid procedures in? > is followed by extra space causing an error.

5. Please strictly limit each line to 120 characters

Excessively long code can cause compatibility problems for displays with multiple resolutions. Also, long code can be hard to read and understand. If it’s too long, wrap the code.

All classes must have a command space

The command space gives the code structure greater clarity and eliminates the problem of conflicts with the same class. You can also use the auto-loading advantages of Composer.

<? php namespace core;Copy the code

A namespace declaration must be followed by a blank line

Empty lines make the code look cleaner and easier to read.

<? php namespace core; use common;Copy the code

8. All import declarations must be placed under namespace declarations

This makes the code structure clear and easy to read.

<? php namespace core; use common;Copy the code

9. There must be only one import keyword in a statement

PHP allows you to import a class using multiple use keywords in a single line of code. However, this can make code reading difficult.

Error:

<? php namespace core; use common, library;Copy the code

Correct:

<? php namespace core; use common; use library;Copy the code

There must be a blank line after the import (use) declaration block

Blank lines make code structure easy to understand.

<? php namespace core; use common; use library; class Person { }Copy the code

11. PHP keywords must be lowercase

The PHP keyword must be lowercase, Boolean values: true, false, null must also be lowercase. The following keywords must also be lowercase:

'__halt_compiler', 'abstract', 'and', 'array', 'as', 'break', 'callable', 'case', 'catch', 'class', 'clone', 'const', 'continue', 'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty', 'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile', 'eval', 'exit', 'extends', 'final', 'for', 'foreach', 'function', 'global', 'goto', 'if', 'implements', 'include', 'include_once', 'instanceof', 'insteadof', 'interface', 'isset', 'list', 'namespace', 'new', 'or', 'print', 'private', 'protected', 'public', 'require', 'require_once', 'return', 'static', 'switch', 'throw', 'trait', 'try', 'unset', 'use', 'var', 'while', 'xor'
Copy the code

12. Inheritance (extends) and implementation (Implement) must be on a line with the class name, and curly braces must be wrapped.

<? php namespace Lib\Databaes; Class Mysql extends ParentClass implements \PDO, \DB //Copy the code

Member attribute access modifiers must display declarations and cannot be omitted

There are three access modifiers for member properties: public, protected, and private. You cannot use old-fashioned var to sound member properties.

<? php namespace Lib\Databaes; Class Mysql extends ParentClass implements \PDO, \DB {public $foo = null; private $name = 'sam'; protected $age = '17'; }Copy the code

Member method access modifiers must display declarations and cannot be omitted

Member methods have three access modifiers: public, protected, and private.

Error:

<?php
namespace Lib\Databases;

class MySQL
{
    function fetchOne()
    {
        // ......
    }
}
Copy the code

Correct:

<?php
namespace Lib\Databases;

class MySQL
{
    public function fetchOne()
    {
        // ......
    }
}
Copy the code

15. When a method has more than one parameter, each parameter must be followed by a space

namespace Lib\Databaes; Class Mysql extends ParentClass implements \PDO, \DB {public getInfo ($name, $age, $gender = 1) {}}Copy the code

16. When using abstract and final class declarations, they must precede the visibility declaration (public or protected or private). When static is used for class declarations, it must come after the visibility declaration.

<? php namespace Vendor\Package; abstract class ClassName { protected static $foo; // static protected function zim(); Public static function bar() public static function bar() {// Method body}}Copy the code

17, control structure curly braces, newline, space and other specifications

If, else, elseif, switch, for, foreach, case, while, go, try, catch and other keywords must be followed by Spaces. It can be said that almost all PHP keywords must be followed by a space unless otherwise specified. The curly braces at the beginning of a flow control statement do not require a separate line.

If ($expr1) {// left space // if body} elseIf ($expr2) {// elesIf ($expr2) {// elseif body} else {// else body; } switch ($expr) {// left blank case 0: echo 'First case, with a break'; / / alignment break; // Line break, also aligned. case 1: echo 'Second case, which falls through'; // no break case 2: case 3: case 4: echo 'Third case, return instead of break'; return; default: echo 'Default case'; break; } while ($expr) {// structure body} do {// structure body; } while ($expr); for ($i = 0; $i < 10; $i++) {for body} foreach ($iterable as $key => $value) {// foreach body} try {// try Body} catch (FirstExceptionType $e) {// Also note Spaces. // catch body } catch (OtherExceptionType $e) { // catch body }Copy the code

18. The class name must be the same as the filename

This is easy to understand, nothing to add. Unless the framework has special loading rules.

Class names must follow the hump naming convention beginning with StudlyCaps

StudlyCaps is the style of uppercase letters. Some people also call it the big hump.

20. Method names must conform to the Camelcase-style camel name convention

CamelCase is the style in which the first word is capitalized after the first letter is lowercase.

21. All letters in class constants must be capitalized and words separated by underscores

CONST ORDER_STATUS = 1;
Copy the code

22. Variables must be named in a small hump style

$cardNo = ''; / / card number. $idCardNo = ''; // Id number.Copy the code

23. Parameters must use the hump naming style

Parameters are also a type of variable. Therefore, it is consistent with the naming style of variables.

All methods must start with a separate line of curly braces.

Although both of the following are allowed in real development. However, to keep the code consistent. Therefore, it must be mandatory.

Error:

<? php class MySQL { public function fetchOne() { } }Copy the code

Correct:

<? php class MySQL { public function fetchOne() { } }Copy the code

25. Write an array parameter directly to a method in the following format

$object->callFunc([
    'userId'   => 1,
    'username' => 'sam',
    'age'      => 20,
    'sex'      => 'male'
]);
Copy the code

26. Method parameter annotation

/** * Manage the background to get the record of sending coupons. * * @author fingerQin 2018-02-23 * @modify fingerQin 2019-02-25 Fixed SQL performance issues. * * @param int $couponId couponId. * @param string $username specifies the username. * @param string $MobilePhone User's mobile number. * @param int $page Specifies the current page number. * @param int $count Specifies the number of entries per page. * @param array $data request parameter. * * -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - eg: start -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- - * $data = [* 'username' = > 'user accounts, no ShiChuanKong string, * 'age' => 'user age', *]; * ------------------- eg:end ----------------------- * * @return array */ public static function getBackendSendHistory($couponId = -1, $username, $mobilephone, $page, $count, $data) { }Copy the code

As you can see, there are several comment features:

1) Method description.

2) Create method colleague number and time.

3) Colleague number and time of modification and modification content of modification method.

4) Parameter note: Type, name, and parameter description. There should be empty lines between parameters and other comments.

5) Parameter example: If there are complex parameters in the parameter. Examples can be provided below the parameters to enhance the illustration.

6) Return value. You need to give the type of return.

27. Methods must have no more than one screen of code

Everyone’s monitor has a different resolution. Since there is no more than one screen will also appear other colleagues will be more than one screen. So, even if you don’t have more than one screen, try to keep your code under 40 lines. If you find yourself with more than 40 lines of code, you need to consider whether your code is unsplit properly. Special cases allow more than 40 lines. However, the code inside the entire method must be simple judgment logic. Does not contain complex business judgment logic. Because different business judgment best practices encapsulate a method separately.