PHP编码规范-PSR0解读

2017-01-08  本文已影响0人  益初

很多时候,我们可以看到国外的框架有有很多特别的写法,但是我们却不明其为什么要这么写,其实他们都是规范于PSR标准。
PSR标准,是又PHP-FIG制定的PHP编码规范

概述

从官方我们可以看到,目前审核通过的规范一共有8套。规范1-4常常被我们在各种文档中看到,但是这些规范的包含的什么,我们却很少知道,这里我就简单的整理一下。

已接受的方案

PSR-0 Basic Coding Standard 基本编码标准

标准内容

1.概述

2.1 PHP Tags

PHP代码 必须 使用长标签 <php ?> 或者短标签<?= ?>

2.2 Character Encoding

PHP代码 必须 使用 不带BOM头的UTF-8编码

2.3 Side Effects

声明文件 应该 不包含会有产生副作用的代码。有产生副作用的代码也不应该包含有声明的情况。

“Side effects” include but are not limited to: generating output, explicit use of require
or include
, connecting to external services, modifying ini settings, emitting errors or exceptions, modifying global or static variables, reading from or writing to a file, and so on.
副作用:包含但不仅限于生成输出,包含 require或者include,连接外部服务器,改变php.ini设置,限制错误信息输出,改变全局或者静态变量,读取或者写入文件。

下面是一个不遵守这规范的例子

<?php
// side effect: change ini settings 副作用:改变ini设置
ini_set('error_reporting', E_ALL);
// side effect: loads a fileinclude "file.php"; 副作用:包含文件
// side effect: generates output 副作用:生成输出
echo "<html>\n";
// declaration 定义:函数
function foo(){ 
// function body
}

下面是一个符合标准的例子,定义一个函数,没有产生副作用的代码

<?php
// declaration 声明foo函数
function foo(){ 
// function body
}
// conditional declaration is *not* a side effect 条件判断不会产生副作用
if (! function_exists('bar')) {
    function bar() { 
    // function body   
    }
}

2.4 Namespace and Class Names

Namespaces和classes名 必须 符合一种自动加载机制。PSR-0或者PSR-4
这其中包含了: 每一个class必须独占一个文件

class names 必须 被命名为 ```StudlyCaps````.
如果代码运行环境是PHP5.3或者更新的,必须使用格式化的namespaces

举个栗子

<?php
// PHP 5.3 and later:
namespace Vendor\Model;
class Foo
{
}

运行环境是5.2或者更古老的,应该 使用伪命名空间

<?php
// PHP 5.2.x and earlier:
//在PSR-0中 下划线"_"会自动被转换成DS "/".用这个原理来自动加载Vendor/Model/Foo文件
class Vendor_Model_Foo 
{
}

2.5 Class Constants, Properties, and Methods

这里的"class"指所有的 classer, interfaces, traits

<?php
namespace Vendor\Model;
class Foo
{
    const VERSION = '1.0';
    const DATE_APPROVED = '2012-06-01';
}

This guide intentionally avoids any recommendation regarding the use of$StudlyCaps
, $camelCase
, or $under_score
property names.
Whatever naming convention is used SHOULD be applied consistently within a reasonable scope. That scope may be vendor-level, package-level, class-level, or method-level.

我大概把他理解为 每一种命名规范至少在某一组织下保持一致

方法名 必须 声明为camelCase

这里就是PSR-1规范的全部内容了,其中classes需要联系着PSR-0或者PSR-4来看。

上一篇下一篇

猜你喜欢

热点阅读