说起码代码,刚上大学那会,老师就教导我们,要严格,规范的,把代码写好。代码如人,工工整整。提起规范化的代码,从一开始用命令行编辑C语言代码就开始控制,强制自己按照相关的标准来,所以,现在写代码,不规范都不行,还是为当时打下的好习惯给自己点个赞。

现在写到了PHP,对于PHP,是否也有相关的代码规范呢,当然,你或许在阅读其他博客或者PHP相关文档的时候经常提到这几个名词,PSR-1,PSR-2之类的,这是PHP-FIG制定的推荐规范,今天,我们就来讲解下PHP的推荐标准,PSR(PHP Standards Recommendation)。

注:PHP-FIG已经废弃了第一份推荐规范,PSR-0,第一份推荐规范被新发布的PSR-4替代了。

PSR-1 : 基本的代码风格 :http://www.php-fig.org/psr/psr-1/

PSR-2 : 严格的代码风格 :http://www.php-fig.org/psr/psr-2/

PSR-3 : 日志记录器接口 :http://www.php-fig.org/psr/psr-3/

PSR-4 : 自动加载 :http://www.php-fig.org/psr/psr-4/

上述网址需要连接vpn方能打开,没有vpn?去买一个吧,一年也就几十块钱。

今天给大家带来的主要是编码规范,PSR-1,PSR-2关于代码风格规范的。

PSR-1 基本代码风格

总览

  • Files MUST use only <?php and <?= tags.

  • Files MUST use only UTF-8 without BOM for PHP code.

  • Files SHOULD either declare symbols (classes, functions, constants, etc.) orcause side-effects (e.g. generate output, change .ini settings, etc.) but SHOULD NOT do both.

  • Namespaces and classes MUST follow an “autoloading” PSR: [PSR-0PSR-4].

  • Class names MUST be declared in StudlyCaps.

  • Class constants MUST be declared in all upper case with underscore separators.

  • Method names MUST be declared in camelCase.

PHP标签

PHP code MUST use the long <?php ?> tags or the short-echo <?= ?> tags; it MUST NOT use the other tag variations.

编码

PHP code MUST use only UTF-8 without BOM.

作用(功能),类、方法、常量不能让人产生歧义

A file SHOULD declare new symbols (classes, functions, constants, etc.) and cause no other side effects, or it SHOULD execute logic with side effects, but SHOULD NOT do both.

The following is an example of a file with both declarations and side effects; i.e, an example of what to avoid:

  1. <?php
  2. // side effect: change ini settings
  3. ini_set('error_reporting', E_ALL);
  4.  
  5. // side effect: loads a file
  6. include "file.php";
  7.  
  8. // side effect: generates output
  9. echo "<html>\n";
  10.  
  11. // declaration
  12. function foo()
  13. {
  14. // function body
  15. }

The following example is of a file that contains declarations without side effects; i.e., an example of what to emulate:

  1. <?php
  2. // declaration
  3. function foo()
  4. {
  5. // function body
  6. }
  7.  
  8. // conditional declaration is *not* a side effect
  9. if (! function_exists('bar')) {
  10. function bar()
  11. {
  12. // function body
  13. }
  14. }

命名空间和类名

Each class is in a file by itself, and is in a namespace of at least one level: a top-level vendor name. The term “class” refers to all classes, interfaces, and traits(性状,类的部分实现).

Code written for PHP 5.3 and after MUST use formal namespaces.

For example:

  1. <?php
  2. // PHP 5.3 and later:
  3. namespace Vendor\Model;
  4.  
  5. class Foo
  6. {
  7. }

常量

Class constants MUST be declared in all upper case with underscore separators. (全部大写,下面可以加下划线)For example:

  1. <?php
  2. namespace Vendor\Model;
  3.  
  4. class Foo
  5. {
  6. const VERSION = '1.0';
  7. const DATE_APPROVED = '2012-06-01';
  8. }

变量

This guide intentionally avoids any recommendation regarding the use of$StudlyCaps$camelCase, or $under_score property names. (枫爷这里建议变量采用下划线,不要使用驼峰命名法)

方法

Method names MUST be declared in camelCase(). (方法命名采用驼峰命名法)

PSR-2 严格代码风格

用官网的话说,这是代码规范,PSR-1只是基本代码规范,如果大家只想要基本的,那下面的内容可以忽略哈,我个人建议还是按照此代码规范来。

总览

  • Code MUST follow a “coding style guide” PSR [PSR-1].

  • Code MUST use 4 spaces for indenting, not tabs.

  • There MUST NOT be a hard limit on line length; the soft limit MUST be 120 characters; lines SHOULD be 80 characters or less.

  • There MUST be one blank line after the namespace declaration, and there MUST be one blank line after the block of use declarations.

  • Opening braces for classes MUST go on the next line, and closing braces MUST go on the next line after the body.

  • Opening braces for methods MUST go on the next line, and closing braces MUST go on the next line after the body.

  • Visibility MUST be declared on all properties and methods; abstract andfinal MUST be declared before the visibility; static MUST be declared after the visibility.

  • Control structure keywords MUST have one space after them; method and function calls MUST NOT.

  • Opening braces for control structures MUST go on the same line, and closing braces MUST go on the next line after the body.

  • Opening parentheses for control structures MUST NOT have a space after them, and closing parentheses for control structures MUST NOT have a space before.

举例

This example encompasses some of the rules below as a quick overview:

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. use FooInterface;
  5. use BarClass as Bar;
  6. use OtherVendor\OtherPackage\BazClass;
  7.  
  8. class Foo extends Bar implements FooInterface
  9. {
  10. public function sampleMethod($a, $b = null)
  11. {
  12. if ($a === $b) {
  13. bar();
  14. } elseif ($a > $b) {
  15. $foo->bar($arg1);
  16. } else {
  17. BazClass::bar($arg2, $arg3);
  18. }
  19. }
  20.  
  21. final public static function bar()
  22. {
  23. // method body
  24. }
  25. }

基础风格

Code MUST follow all rules outlined in PSR-1.

文件

All PHP files MUST use the Unix LF (linefeed) line ending.

All PHP files MUST end with a single blank line.

The closing ?> tag MUST be omitted from files containing only PHP.

或许你之前也写过PHP的代码,这里,PHP文件的最后不许要有空行,而且不允许使用?>结尾标签。

代码行长度

Lines SHOULD NOT be longer than 80 characters; lines longer than that SHOULD be split into multiple subsequent lines of no more than 80 characters each.

缩进

Code MUST use an indent of 4 spaces, and MUST NOT use tabs for indenting.

N.b.: Using only spaces, and not mixing spaces with tabs, helps to avoid problems with diffs, patches, history, and annotations. The use of spaces also makes it easy to insert fine-grained sub-indentation for inter-line alignment.

关键字

PHP keywords MUST be in lower case.

The PHP constants truefalse, and null MUST be in lower case.

命名空间

When present, there MUST be one blank line after the namespace declaration.

When present, all use declarations MUST go after the namespace declaration.

There MUST be one use keyword per declaration.

There MUST be one blank line after the use block.

For example:

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. use FooClass;
  5. use BarClass as Bar;
  6. use OtherVendor\OtherPackage\BazClass;
  7.  
  8. // ... additional PHP code ...

Extends和Implements

The extends and implements keywords MUST be declared on the same line as the class name.

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. use FooClass;
  5. use BarClass as Bar;
  6. use OtherVendor\OtherPackage\BazClass;
  7.  
  8. class ClassName extends ParentClass implements \ArrayAccess, \Countable
  9. {
  10. // constants, properties, methods
  11. }

变量

Visibility(public、private、protected) MUST be declared on all properties.

The var keyword MUST NOT be used to declare a property.

There MUST NOT be more than one property declared per statement.

Property names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility. 这里是SHOULD NOT,我个人觉得应该是MUST NOT。

A property declaration looks like the following.

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. class ClassName
  5. {
  6. public $foo = null;
  7. }

方法

Visibility MUST be declared on all methods.

Method names SHOULD NOT be prefixed with a single underscore to indicate protected or private visibility. 这里是SHOULD NOT,我个人觉得应该是MUST NOT。

The opening brace MUST go on its own line, and the closing brace MUST go on the next line following the body.

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. class ClassName
  5. {
  6. public function fooBarBaz($arg1, &$arg2, $arg3 = [])
  7. {
  8. // method body
  9. }
  10. }

方法参数

In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.

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

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. class ClassName
  5. {
  6. public function foo($arg1, &$arg2, $arg3 = [])
  7. {
  8. // method body
  9. }
  10. }

When the argument list is split across multiple lines, the closing parenthesis and opening brace MUST be placed together on their own line with one space between them.

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. class ClassName
  5. {
  6. public function aVeryLongMethodName(
  7. ClassTypeHint $arg1,
  8. &$arg2,
  9. array $arg3 = []
  10. ) {
  11. // method body
  12. }
  13. }

abstract, final, and static

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

When present, the static declaration MUST come after the visibility declaration.

  1. <?php
  2. namespace Vendor\Package;
  3.  
  4. abstract class ClassName
  5. {
  6. protected static $foo;
  7.  
  8. abstract protected function zim();
  9.  
  10. final public static function bar()
  11. {
  12. // method body
  13. }
  14. }

方法调用

When making a method or function call,

there MUST NOT be a space between the method or function name and the opening parenthesis,

there MUST NOT be a space after the opening parenthesis, and there MUST NOT be a space before the closing parenthesis.

In the argument list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.

  1. <?php
  2. bar();
  3. $foo->bar($arg1);
  4. Foo::bar($arg2, $arg3);

控制结构

  • There MUST be one space after the control structure keyword
  • There MUST NOT be a space after the opening parenthesis
  • There MUST NOT be a space before the closing parenthesis
  • There MUST be one space between the closing parenthesis and the opening brace
  • The structure body MUST be indented once
  • The closing brace MUST be on the next line after the body

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.

  1. <?php
  2. if ($expr1) {
  3. // if body
  4. } elseif ($expr2) {
  5. // elseif body
  6. } else {
  7. // else body;
  8. }

switch, case

switch structure looks like the following. There MUST be a comment such as // no break when fall-through is intentional in a non-empty case body.

  1. <?php
  2. switch ($expr) {
  3. case 0:
  4. echo 'First case, with a break';
  5. break;
  6. case 1:
  7. echo 'Second case, which falls through';
  8. // no break
  9. case 2:
  10. case 3:
  11. case 4:
  12. echo 'Third case, return instead of break';
  13. return;
  14. default:
  15. echo 'Default case';
  16. break;
  17. }

while, do while

  1. <?php
  2. while ($expr) {
  3. // structure body
  4. }
  1. <?php
  2. do {
  3. // structure body;
  4. } while ($expr);

for, foreach

  1. <?php
  2. for ($i = 0; $i < 10; $i++) {
  3. // for body
  4. }
  1. <?php
  2. foreach ($iterable as $key => $value) {
  3. // foreach body
  4. }

try, catch

  1. <?php
  2. try {
  3. // try body
  4. } catch (FirstExceptionType $e) {
  5. // catch body
  6. } catch (OtherExceptionType $e) {
  7. // catch body
  8. }

匿名函数

Closures MUST be declared with a space after the function keyword, and a space before and after the use keyword.

The opening brace MUST go on the same line, and the closing brace MUST go on the next line following the body.

There MUST NOT be a space after the opening parenthesis of the argument list or variable list, and there MUST NOT be a space before the closing parenthesis of the argument list or variable list.

In the argument list and variable list, there MUST NOT be a space before each comma, and there MUST be one space after each comma.

Closure arguments with default values MUST go at the end of the argument list.

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

  1. <?php
  2. $closureWithArgs = function ($arg1, $arg2) {
  3. // body
  4. };
  5.  
  6. $closureWithArgsAndVars = function ($arg1, $arg2) use ($var1, $var2) {
  7. // body
  8. };

那些个参数换行的写法这里就不介绍了,感觉那样子会让代码乱糟糟的,个人不建议那么做,方法的参数一定要写注释,注释相当重要,宁愿舍弃点规范,也要多写注释,规范少写一点,大不了可读性差点,如果注释少些点,那就根本读不了了。

好了,今天关于PSR-1和PSR-2对于代码的规范就说到这,接下来我会给大家带来PSR-3日志规范和PSR-4自动加载器相关内容。良好的开端是成功的基本要素,希望大家能好好遵守代码规范,毕竟代码如人,工工整整嘛。^_^

【PHP系列】PHP推荐标准之PSR-1,PSR-2的更多相关文章

  1. 【PHP系列】PHP推荐标准之PSR-3,日志记录器接口

    上节聊完了PHP官方的相关代码规范,下面给大家带来了PHP系列的PHP推荐标准的另外两个,PSR-3,PSR-4. 首先,我们先来了解下PSR-3是怎么回事. PHP-FIG发布的第三个推荐规范与前两 ...

  2. Atitit 提升效率 界面gui方面的前后端分离与cbb体系建设 规范与推荐标准

    Atitit 提升效率 界面gui方面的前后端分离与cbb体系建设 规范与推荐标准 1. 界面gui方面的前后端分离重大意义1 2. 业务逻辑也适当的迁移js化1 3. 常用分离方法2 3.1. 页面 ...

  3. Atitit 我们的devops战略与规划 规范 推荐标准

    Atitit 我们的devops战略与规划 规范 推荐标准 1. Vm容器化1 2. 热部署tomcat+jrebel 或者resin1 3. 增量更新与差异更新1 4. 补丁提取与应用2 为了方便提 ...

  4. [译]新的CCSDS图像压缩推荐标准

    摘要——空间数据系统咨询委员会(CCSDS)的数据压缩工作组最近通过了图像数据压缩议案,最终版本预计在2005年发布.议案中采用的算法由两部分组成,先是一个对图像的二维离散小波变换,然后是对变换后的数 ...

  5. Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  6. Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  7. Keil MDK STM32系列(三) 基于标准外设库SPL的STM32F407开发

    Keil MDK STM32系列 Keil MDK STM32系列(一) 基于标准外设库SPL的STM32F103开发 Keil MDK STM32系列(二) 基于标准外设库SPL的STM32F401 ...

  8. 【PHP系列】PHP推荐标准之PSR-4,自动加载器策略

    接上回的继续说,上回说到PSR-3日志记录器接口,这回我们来说说PSR的最后一个标准,PSR-4,自动加载器策略. 缘由 自动加载器策略是指,在运行时按需查找PHP类.接口或性状,并将其载入PHP解释 ...

  9. Go 的 golang.org/x/ 系列包和标准库包有什么区别?

    在开发过程中可能会遇到这样的情况,有一些包是引入自不同地方的,比如: golang.org/x/net/html 和 net/html, golang.org/x/crypto 和 crypto. 那 ...

随机推荐

  1. DataTabel DataSet 对象 转换成json

    public class DataTableConvertJson    { #region dataTable转换成Json格式        /// <summary>         ...

  2. Ubuntu切换默认语言

    不得不说,从Ubuntu到Debian,又到CentOS 7,我胡汉三又回来了... 然后又装了个中文版的Ubuntu16.04LTS,不得不说,Ubuntu对中文的支持真的很好 不过,还是不太习惯, ...

  3. Redis client Python usage

    http://www.yiibai.com/redis/redis_sorted_sets.html mport redis r_server = redis.Redis('localhost') # ...

  4. MindManager 安装注册

    正版现在998元,对于个人用户来说是不是太贵了.直接下载的还不能打开,挺奇怪.

  5. 利用 Grunt (几乎)无痛地做前端开发 (一)之单元测试

    前言 如果你想开发一个js应用,甭管多简单,都要先创建整个宇宙 来看看我们的Javascript小宇宙: 确定如何根据需求.功能划分模块,如何将代码分成多个文件开发,合成一个发布 保证上一条的同时,使 ...

  6. angular指令中,require和transclude同时设置为true时的作用

    最近在学习angularJS指令的时候,对指令对象中require属性和transclude属性同时设置为true比较疑惑,于是自己动手测试一下具体差异 index.html: <simple& ...

  7. JQuery flot API文档 中文版

    调用plot函数的方法如下: var plot = $.plot(placeholder, data, options) 其 中placeholder可以是JQuery的对象,DOM元素或者JQuer ...

  8. HTML <div> 和<span>

    HTML <div> 和<span> HTML 可以通过 <div> 和 <span>将元素组合起来. HTML 区块元素 大多数 HTML 元素被定义 ...

  9. Spring mvc 数据验证

    加入jar包 bean-validator.jar 在实体类中加入验证Annotation和消息提示 package com.stone.model; import javax.validation. ...

  10. MyBatis 一级、二级缓存

    一级 默认session就有一级缓存,session有C/U/D操作或者session.clearCache();session.commit();都会清空缓存: 二级在mapper.xml中添加&l ...