Home  >  Article  >  Backend Development  >  PHP code style style specification sharing

PHP code style style specification sharing

小云云
小云云Original
2018-03-05 10:30:424185browse

This article mainly shares PHP code style specifications with you, hoping to help everyone.

1. Basic Agreements

1. Source files

(1). Pure PHP code source files only use the ;

(2). The encoding format of the PHP code in the source file must be UTF-8 format without BOM;

(3) Use Unix LF (line feed) as the line terminator;

(4). One source file only makes one type of declaration, that is, this file is specially used to declare Class, and that file is specially used to set configuration information. Do not write them together;

2. Indentation

Use the Tab key to indent, and set the length of each Tab key to 4 spaces;

3. Line

It is recommended to write a maximum of 120 characters. If it exceeds this number, it should be wrapped. It can be set by a general editor.

//wo

Fill up the horizontal scrolling and vertical scrolling,

4, keywords and True/False/Null

The key to PHP Words must be lowercase, and boolean values: true, false, and null must also be lowercase.

The following are the "keywords" of PHP, which must 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'

5. Naming

(1), the class name is written in StudlyCaps;

(2), the method name (of the class) is written in cameCase;

( 3) Use lowercase letters + underscores for function names, such as function http_send_post();

(4) Use small camel case for variable names, such as $userName;

6. Code comment tags

Such as function comments, variable comments, etc. Commonly used tags include @package, @var, @param, @return, @author, @todo, @throws

Must comply with phpDocument tag rules, do not In addition, create new tags. For more tags, check phpDocument official website

7, business module

(1), when involving multiple data table update/add operations, the outermost layer should be used Transactions ensure the atomicity of database operations;

(2), Model layer, only perform simple data table queries;

(3), business logic is uniformly encapsulated into the Logic layer;

(4). The controller only does URL routing, do not call it as a business method;

(5). SQL operation statements cannot appear in the controller layer, such as where(), order() and other model methods,

That is, in the controller, do not have SQL statements like this: D('XXX')->where()->order()->limit( )->find();

SQL methods such as where(), order(), limit(), etc. can only appear in the Model layer and business layer!

2. Code style

1. Namespace (Namespace) and import (Use) declaration

Let’s briefly describe it in text:

  1. There must be a blank line after the namespace declaration;

  2. All import (use) declarations must be placed below the namespace declaration;

  3. There must be only one import (use) keyword in a statement;

  4. There must be an empty line after the import (use) declaration code block OK;

Use code to illustrate:

1

2

3

4

5

6

##

namespace Lib\Databases; // There must be a blank line below

class Mysql {

}

If you leave a blank line under namespace, you can use use, and if you leave another blank line, you can declare class

2. Class, property and method

(1), inheritance (extends) and implementation (implement) must be written on the same line as the class name.

1

2

3

4

5

6

7

8

9

10

namespace Lib\Databases; // There must be a blank line below

use FooInterface; // use must be declared after namespace

use BarClass as Bar;

use OtherVendor\OtherPackage\BazClass; // There must be a blank line below

class Mysql {

}

1

2

3

4

5

6

namespace Lib\Databaes;

class Mysql extends ParentClass implementations \PDO , \DB { // Write a line

}

(2), the property must declare its Visibility, whether it is public, protected or private, cannot be omitted, nor can var be used. What method is var used in the old version of PHP, etc. for public.

1

2

3

4

5

6

7

8

namespace Lib\Databaes;

class Mysql extends ParentClass implementations \PDO, \DB { // Write a line

public $foo = null;

private $name = 'yangyi';

protected $age = '17';

}

(3) Method (method) must declare its visibility, whether it is public, protected or private, it cannot be omitted. If there are multiple parameters, follow the first parameter with "," and add a space: function_name ($par, $par2, $pa3). If the parameter has a default value, separate it with a space on the left and right of "=".

1

2

3

4

5

6

7

8

namespace Lib\Databaes;

class Mysql extends ParentClass implementations \PDO, \DB { // Write a line

public getInfo($name, $age, $gender = 1) { // There is one between the parameters Space. There is a space to the left and right of "=" in the default parameter, and there is a space between ) and {

}

}

(4) When abstract and final are used to make class declarations, they must be placed in front of the visibility declaration (public, protected or private). When static is used for class declaration, it must be placed after the visibility declaration.

Directly upload the code:

##

3. Control structure

The control interface is if else while switch, etc. This type of writing standard is often prone to problems, so it should be standardized.

(1) If, elseif, else writing method, just go to the standard code:

##1

2

3

4

5

6

7

8

9

10

11

namespace Vendor\Package;

abstract class ClassName {

protected static $foo; // put static in the back

abstract protected function zim(); // put abstract in front

final public static function bar() { // final In the front, static is placed last.

//Method body part

}

}

1

2

3

4

5

6

7

8

if ($expr1) { // There is a space between if and (, there is a space between ) and {

} elseif ($expr2) { // elesif is written continuously, there is a space between (,) and { There is a space between

} else { // else left and right A space

}

##(2), switch, case Pay attention to spaces and line breaks, or go directly to the standard code :

##1

(3), while, do while are written similarly, the above code is:

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

##
switch ($expr) { //There is a space between switch and (, there is a space between) and {

case 0:

echo 'First case, with a break'; // Alignment

               break; //                                                                                                                                  break

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;

}

1

2

3

4

5

6

7

8

< ;?php

while ($expr) { // There is a space between while and (, there is a space between ) and {

}

do { // There is a space between do and {

} while ($expr); // There is a space on the left and right side of while

(4) How to write for

##

for ($i = 0; $i < 10; $i++ ) { // There is a space between for and (, there is a space on the left and right of the binary operators "=", "<", there is a space between ) and {

}

(5), how to write foreach

##1

2

3

4

##1

2

3

4

foreach ($iterable as $key => $value) { // There is a space between foreach and (, "=> There is a space on the left and right of ;", and there is a space between ) and {

}

(6) , How to write try catch

4. Comment

(1), Line comment

// needs to be followed by a space;

If there is a non-empty character in front of //, then // A space needs to be added in front;

(2), function comments

The text of parameter names, attribute names, and labels must be aligned up and down;

is added before the first label A blank line;

1

2

3

4

5

6

7

8

try { // try There is a space on the right

} catch (FirstExceptionType $e) { // There is a space between catch and (, there is a space between) and {

} catch (OtherExceptionType $e) { // There is a space between catch and (, there is a space between ) and {

}

##

/**

 * This is a sample function to illustrate additional PHP

 * formatter options.

 *

 * @param        $one   The first parameter

 * @param int    $two   The second parameter

 * @param string $three The third parameter with a longer

 *                      comment to illustrate wrapping.

 * @return void

 * @author  phpgo.cnblogs.com

 * @license GPL

 */

function foo($one, $two = 0, $three = "String") {

}

5, spaces

(1), assignment operators (=, +=, etc.), logical operators (&&, ||), equal sign operators (==, !=), relationships Operators (<, >, <=, >=), bitwise operators (&, |, ^), connectors (.) There is a space on the left and right;

(2) , if, else, elseif, while, do, switch, for, foreach, try, catch, finally, etc. There is a space between the immediate left bracket "(";

(3), function, Between the various parameters of the method, there is a space after the comma (",");

6, blank line

(1), all left curly brackets { do not wrap, and { is tight Next to it, it must not be a blank line;

(2), there must be a blank line in front of the comments (line comments/block comments) of the same level code (same indentation);

(3), there is a blank line between each method/function;

(4), there is a blank line between the namespace statement, use statement, and clase statement;

(5) , return statement

If there is only one line of PHP code before the return statement, there is no need for a blank line before the return statement;

If there are at least two lines of PHP code before the return statement, add a blank line before the return statement ;

There is a blank line between (5), if, while, switch, for, foreach, try and other code blocks and between other codes;


【Reference example summary】

Reference 1:

##1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

1

2

3

4

5

6

7

8

namespace Lib\Databaes;

class Mysql extends ParentClass implementations \PDO, \DB { // Write a line

public getInfo($name, $age, $gender = 1) { // There is a space between the parameters. There is a space on the left and right side of the default parameter "=", and there is a space between ) and {

}

}

Reference 2:

##

参考3:

1

2

3

4

5

6

7

8

9

10

11

namespace Vendor\Package;

abstract class ClassName {

protected static $foo; / / static is placed at the back

abstract protected function zim(); // abstract is placed at the front

final public static function bar() { // final is placed at the front, static is placed at the front at last.

//Method body part

}

}

参考4:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

namespace library\Model;

 

use library\Helper\ImageHelper;

use library\Logic\UserMainLogic;

 

/**

* User table data model

*

* @package library\Model

*/

class UserMainModel extends BasicModel {

     /**

* Get user statistical information

*

* @param int $userId User ID

* @return array

*/

    public function getUserCard($userId) {

        $userId = intval($userId);

        return UserMainLogic::instance()->getUserCard($userId);

    }

 

    /**

* Get user information based on Id

* @param int $userId UserId

* @param string $field Display field

* @return array

*/

    public function getByUserId($userId = 0, $field = '*') {

        if (empty($userId)) {

            return array();

        }

 

        $where = array('id' => $userId);

        $info = $this->field($field)->where($where)->find();

 

        if (isset($info['image']) && isset($info['sex'])) {

            $info['image'] = ImageHelper::GetImageUrl($info['image'], $info['sex']);

        }

 

        return $info;

    }

}

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

$serv = new swoole_server("127.0.0.1", 9502);

 

// sets server configuration, we set task_worker_num config greater than 0 to enable task workers support

$serv->set(array('task_worker_num' => 4));

 

// attach handler for receive event, which have explained above.

$serv->on('receive', function($serv, $fd, $from_id, $data) {

    // we dispath a task to task workers by invoke the task() method of $serv

    // this method returns a task id as the identity of ths task

    $task_id = $serv->task($data);

    echo "Dispath AsyncTask: id=$task_id\n";

});

 

// attach handler for task event, the handler will be executed in task workers.

$serv->on('task', function ($serv, $task_id, $from_id, $data) {

    // handle the task, do what you want with $data

    echo "New AsyncTask[id=$task_id]".PHP_EOL;

 

    // after the task task is handled, we return the results to caller worker.

    $serv->finish("$data -> OK");

});

 

// attach handler for finish event, the handler will be executed in server workers, the same worker dispatched this task before.

$serv->on('finish', function ($serv, $task_id, $data) {

    echo "AsyncTask[$task_id] Finish: $data".PHP_EOL;

});

 

$serv->start();

Summary: All left curly brackets { do not break lines, and { immediately below must not be a blank line!

The above code style specifications refer to the specifications of Java, JavaScript, Objective-C, Go and other development languages!

The Java language has had a profound impact on Chinese programmers, and most people are still used to leaving the left curly brace { without a newline!

Writing principles: Make the code compact without losing small modularity!

PSR-4 specification

The PSR-4 specification is a new specification that just came out. It also regulates automatic loading (autoload). The modifications to PSR-0 are supplementary specifications.

I will briefly mention them, mainly the following points:

  1. The abolition of PSR-0 is directory splitting In the way of writing symbols, _underscore has no special meaning in fully qualified class names.

  2. The class file name must end with .php.

  3. The class name must be exactly the same as the corresponding file name, and the case must be exactly the same.

Reference:

Code style research: Is the left curly brace wrapped in a new line? ? ?

PSR-[0-4] code specification in PHP

[Supplementary] Array writing format

When there is only one key-value pair, write it in one line:

1

$where = array('id' => 789);

When there are multiple (two or more) key-value pairs, wrap the line:

Related recommendations:

ThinkPHP 3.2.3 Paging code style sharing

PHP code style

PHP documentation on coding standards (collection)

1

2

3

4

##$where = array(

'id' => 789,

'user_name' => 'phpgo'

);

The above is the detailed content of PHP code style style specification sharing. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn