Codeigniter 3

PHP风格指南 | PHP Style Guide

PHP Style Guide

以下页面描述了对开发CodeIgniter时所遵循的编码风格。不要求在你自己的CodeIgniter应用程序中使用这些样式,尽管它们是推荐的。

目录

  • PHP风格指南

- [PHP Closing Tag](about:blank#php-closing-tag) - [File Naming](about:blank#file-naming) - [Class and Method Naming](about:blank#class-and-method-naming) - [Variable Names](about:blank#variable-names) - [Commenting](about:blank#commenting) - [Constants](about:blank#constants) - [TRUE, FALSE, and NULL](about:blank#true-false-and-null) - [Logical Operators](about:blank#logical-operators) - [Comparing Return Values and Typecasting](about:blank#comparing-return-values-and-typecasting) - [Debugging Code](about:blank#debugging-code) - [Whitespace in Files](about:blank#whitespace-in-files) - [Compatibility](about:blank#compatibility) - [One File per Class](about:blank#one-file-per-class) - [Whitespace](about:blank#whitespace) - [Line Breaks](about:blank#line-breaks) - [Code Indenting](about:blank#code-indenting) - [Bracket and Parenthetic Spacing](about:blank#bracket-and-parenthetic-spacing) - [Localized Text](about:blank#localized-text) - [Private Methods and Variables](about:blank#private-methods-and-variables) - [PHP Errors](about:blank#php-errors) - [Short Open Tags](about:blank#short-open-tags) - [One Statement Per Line](about:blank#one-statement-per-line) - [Strings](about:blank#strings) - [SQL Queries](about:blank#sql-queries) - [Default Function Arguments](about:blank#default-function-arguments)

文件格式

文件应该用Unicode(UTF-8)编码保存。该BOM应该被使用。与UTF-16和UTF-32同,UTF-8编码文件中没有字节顺序指示,并且BOM在发送输出的PHP中可能具有负面影响,阻止应用程序能够设置它自己的标题。应使用Unix行结尾(LF)。

以下是如何在一些更常见的文本编辑器中应用这些设置。您的文本编辑器的说明可能有所不同 检查你的文本编辑器的文档。

TextMate

  • 打开应用程序首选项

BBEdit

  • 打开应用程序首选项

PHP关闭标签

PHP文档?>上的PHP结束标记对PHP解析器是可选的。但是,如果使用了关闭标记之后的任何空格,无论是由开发人员,用户还是FTP应用程序引入,都可能导致不需要的输出,PHP错误或者后者被抑制的空白页面。出于这个原因,所有的PHP文件都必须OMIT PHP结束标记,并以一个空行结束。

文件命名

类文件必须以类似Ucfirst的方式命名,而任何其他文件名(配置,视图,通用脚本等)都应该全部小写。

错误

somelibrary.php someLibrary.php SOMELIBRARY.php Some_Library.php Application_config.php Application_Config.php applicationConfig.php

正确

Somelibrary.php Some_library.php applicationconfig.php application_config.php

此外,类文件名应该与类本身的名称匹配。例如,如果您有一个名为class的类Myclass,那么它的文件名必须是Myclass.php

类和方法命名

类名称应始终以大写字母开头。多个单词应该用下划线分隔,而不是CamelCased。

错误

class superclass class SuperClass

正确

class Super_class

class Super_class { public function __construct() { } }

类方法应该完全小写和命名以清楚地表明它们的功能,最好包括一个动词。尽量避免使用过长和冗长的名字。多个单词应该用下划线分隔。

错误

function fileproperties() // not descriptive and needs underscore separator function fileProperties() // not descriptive and uses CamelCase function getfileproperties() // Better! But still missing underscore separator function getFileProperties() // uses CamelCase function get_the_file_properties_from_the_file() // wordy

正确

function get_file_properties() // descriptive, underscore separator, and all lowercase letters

变量名称

变量命名的准则与用于类方法的准则非常相似。变量应该只包含小写字母,使用下划线分隔符,并且应合理命名以表示其用途和内容。非常短的非单词变量只能用作for()循环中的迭代器。

错误

$j = 'foo'; // single letter variables should only be used in for() loops $Str // contains uppercase letters $bufferedText // uses CamelCasing, and could be shortened without losing semantic meaning $groupid // multiple words, needs underscore separator $name_of_last_city_used // too long

正确

for ($j = 0; $j < 10; $j++) $str $buffer $group_id $last_city

评论

一般来说,代码应该被大量地评论。它不仅有助于描述缺乏经验的程序员的代码的流程和意图,而且可以在数月后返回自己的代码时证明是非常宝贵的。没有必要的评论格式,但推荐使用以下格式。

DocBlock样式注释在类,方法和属性声明之前,以便它们可以被IDE拾取:

/** * Super Class * * @package Package Name * @subpackage Subpackage * @category Category * @author Author Name * @link http://example.com */ class Super_class {

/** * Encodes string for use in XML * * @param string $str Input string * @return string */ function xml_encode($str)

/** * Data for class manipulation * * @var array */ public $data = array(

在代码中使用单行注释,在大注释块和代码之间留下空行。

// break up the string by newlines $parts = explode("\n", $str // A longer comment that needs to give greater detail on what is // occurring and why can use multiple single-line comments. Try to // keep the width reasonable, around 70 characters is the easiest to // read. Don't hesitate to link to permanent external resources // that may provide greater detail: // // http://example.com/information_about_something/in_particular/ $parts = $this->foo($parts

常量

常量遵循与变量相同的准则,除了常量应该总是全部大写。适当时应始终使用CodeIgniter常量,即SLASH,LD,RD,PATH_CACHE等。

错误

myConstant // missing underscore separator and not fully uppercase N // no single-letter constants S_C_VER // not descriptive $str = str_replace('{foo}', 'bar', $str // should use LD and RD constants

正确

MY_CONSTANT NEWLINE SUPER_CLASS_VERSION $str = str_replace(LD.'foo'.RD, 'bar', $str

TRUE,FALSE和NULL

TRUEFALSENULL关键字应始终为大写。

错误

if ($foo == true) $bar = false; function foo($bar = null)

正确

if ($foo == TRUE) $bar = FALSE; function foo($bar = NULL)

逻辑运算符

||不鼓励使用“或”比较运算符,因为它在某些输出设备上的清晰度较低(例如,看起来像数字11)。&&是优先的,AND但任何一个都是可以接受的,空间应该总是在前后!

错误

if ($foo || $bar) if ($foo AND $bar) // okay but not recommended for common syntax highlighting applications if (!$foo) if (! is_array($foo))

正确

if ($foo OR $bar) if ($foo && $bar) // recommended if ( ! $foo) if ( ! is_array($foo))

比较返回值和类型转换

有些PHP函数在失败时返回FALSE,但也可能有一个有效的返回值“”或0,这将在松散比较中评估为FALSE。在条件中使用这些返回值时,通过比较变量类型来确保返回值确实是您期望的,而不是具有等效松散类型评估的值时,请通过比较显式。

在返回和检查自己的变量时使用相同的严格性。根据需要使用===!==

错误

// If 'foo' is at the beginning of the string, strpos will return a 0, // resulting in this conditional evaluating as TRUE if (strpos($str, 'foo') == FALSE)

正确

if (strpos($str, 'foo') === FALSE)

错误

function build_string($str = "") { if ($str == "") // uh-oh! What if FALSE or the integer 0 is passed as an argument? { } }

正确

function build_string($str = "") { if ($str === "") { } }

另请参阅有关类型转换的信息,这可能非常有用。类型转换具有可能需要的稍微不同的效果。例如,当将一个变量作为一个字符串转换时,NULL和布尔FALSE变量变为空字符串,0(和其他数字)变成数字串,布尔值TRUE变为“1”:

$str = (string) $str; // cast $str as a string

调试代码

不要在提交时留下调试代码,即使注释掉了。世事如var_dump()print_r()die()/ exit()不应该包括在你的代码,除非它提供比其他调试特定的目的。

文件中的空白

没有空格可以在开始的PHP标签之前或跟随关闭的PHP标签。输出被缓冲,因此文件中的空白可能导致输出在CodeIgniter输出其内容之前开始输出,从而导致错误和CodeIgniter无法发送正确的标题。

兼容性

CodeIgniter建议使用PHP 5.6或更高版本,但它应该与PHP 5.3.7兼容。您的代码必须与此要求兼容,提供合适的回退功能,或者是一个可选功能,可以在不影响用户应用程序的情况下安静地死去。

另外,不要使用需要安装非默认库的PHP函数,除非您的代码在函数不可用时包含替代方法。

每个类一个文件

对每个班级使用单独的文件,除非班级密切相关。一个包含多个类的CodeIgniter文件的例子是Xmlrpc库文件。

Whitespace

在代码中使用制表符而不是空格。这可能看起来像一件小事,但使用制表符而不是空格允许开发人员查看您的代码,在他们使用的任何应用程序中他们喜欢和定制的级别具有缩进。作为一个副作用,它会产生(稍微)更紧凑的文件,存储一个制表符,比如说四个空格字符。

换行

必须使用Unix换行符保存文件。这对于在Windows中工作的开发人员而言更是一个问题,但无论如何,请确保您的文本编辑器设置为使用Unix换行符保存文件。

代码缩进

使用Allman风格缩进。除了Class声明之外,花括号总是自己放在一行上,并在与“拥有”控制语句相同的级别上缩进。

错误

function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } } try { // ... } catch() { // ... }

正确

function foo($bar) { // ... } foreach ($arr as $key => $val) { // ... } if ($foo == $bar) { // ... } else { // ... } for ($i = 0; $i < 10; $i++) { for ($j = 0; $j < 10; $j++) { // ... } } try { // ... } catch() { // ... }

括号和括号间隔

一般来说,括号和括号不应该使用任何额外的空格。例外是空间应该总是遵循PHP控制结构,它接受括号括起来的参数(声明,do-while,elseif,for,foreach,if,switch,while),以帮助区分它们和函数并提高可读性。

错误

$arr[ $foo ] = 'foo';

正确

$arr[$foo] = 'foo'; // no spaces around array keys

错误

function foo ( $bar ) { }

正确

function foo($bar) // no spaces around parenthesis in function declarations { }

错误

foreach( $query->result() as $row )

正确

foreach ($query->result() as $row) // single space following PHP control structures, but not in interior parenthesis

本地化文本

CodeIgniter库应尽可能利用相应的语言文件。

错误

return "Invalid Selection";

正确

return $this->lang->line('invalid_selection'

私有方法和变量

只能在内部访问的方法和变量(例如公用方法用于代码抽象的实用程序和辅助函数)应该以下划线作为前缀。

public function convert_text() private function _convert_text()

PHP错误

代码必须运行无误,并且不要依赖警告和通知来隐藏以满足此要求。例如,不要先查看你没有设置的变量(比如$_POST数组键),而是先不检查它isset()

确保您的开发环境为所有用户启用了错误报告,并且在PHP环境中启用了display_errors。您可以通过以下方式检查此设置

if (ini_get('display_errors') == 1) { exit "Enabled"; }

在禁用display_errors的某些服务器上,如果您无法在php.ini中更改此设置,则可以通过以下方法启用它:

ini_set('display_errors', 1

注意

在运行时设置display_errors设置与ini_set()在PHP环境中启用display_errors设置不同。也就是说,如果剧本有致命的错误,它不会有任何效果。

短打开标签

如果服务器没有启用short_open_tag,则始终使用完整的PHP开始标记。

错误

<? echo $foo; ?> <?=$foo?>

正确

<?php echo $foo; ?>

注意

PHP 5.4 will always have the <?= tag available.

每行一条语句

不要在一行上合并语句。

错误

$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag

正确

$foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag

字符串

除非需要分析变量,否则总是使用单引号字符串,并且在确实需要分析变量的情况下,使用花括号来防止贪婪令牌解析。如果字符串包含单引号,则也可以使用双引号字符串,因此不必使用转义字符。

错误

"My String" // no variable parsing, so no use for double quotes "My string $foo" // needs braces 'SELECT foo FROM bar WHERE baz = \'bag\'' // ugly

正确

'My String' "My string {$foo}" "SELECT foo FROM bar WHERE baz = 'bag'"

SQL查询

SQL关键字总是大写:SELECT,INSERT,UPDATE,WHERE,AS,JOIN,ON,IN等。

将冗长的查询分解为多行,以便易读,最好是为每个子句打破。

错误

// keywords are lowercase and query is too long for // a single line (... indicates continuation of line) $query = $this->db->query("select foo, bar, baz, foofoo, foobar as raboof, foobaz from exp_pre_email_addresses ...where foo != 'oof' and baz != 'zab' order by foobaz limit 5, 100"

正确

$query = $this->db->query("SELECT foo, bar, baz, foofoo, foobar AS raboof, foobaz FROM exp_pre_email_addresses WHERE foo != 'oof' AND baz != 'zab' ORDER BY foobaz LIMIT 5, 100"

默认函数参数

在适当的时候,提供函数参数默认值,这有助于防止错误调用PHP错误,并提供可以节省几行代码的常见回退值。例:

function foo($bar = '', $baz = FALSE)