(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;
Use the Tab key to indent, and set the length of each Tab key to 4 spaces;
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,
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'
(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;
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
(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!
Let’s briefly describe it in text:
There must be a blank line after the namespace declaration;
All import (use) declarations must be placed below the namespace declaration;
There must be only one import (use) keyword in a statement;
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 { } |
123456 78910 | 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:
##1234 567891011 | 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 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
##1234 | ##
##1234 | 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 { } |
12345678 | 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 { } |
##1234 56789101112 13141516 | ##
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:
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 } } |
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!
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:
The abolition of PSR-0 is directory splitting In the way of writing symbols, _underscore has no special meaning in fully qualified class names.
The class file name must end with .php.
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
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:
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!