• CodeIgniter 开发规范


    CodeIgniter 开发规范
    2011-03-26 16:38
    文件格式

    文件应该使用 Unicode (UTF-8) 编码保存。同时不要使用 字节序标记(BOM) 。与 UTF-16 和 UTF-32 不同,UTF-8 编码的文件不需要指明字节序,而且 字节序标记(BOM) 在PHP中会产生预期之外的输出,阻止了应用程序设置它自己的头信息。应该使用Unix 格式的行结束符(LF)。


    PHP 闭合标签

    PHP闭合标签“?>”在PHP中对PHP的分析器是可选的。 但是,如果使用闭合标签,任何由开发者,用户,或者FTP应用程序插入闭合标签后面的空格都有可能会引起多余的输出、php错误、之后的输出无法显示、空白页。因此,所有的php文件应该省略这个php闭合标签,并插入一段注释来标明这是文件的底部并定位这个文件在这个应用的相对路径。这样有利于你确定这个文件已经结束而不是被删节的。
    INCORRECT:
    <?php

    echo "Here's my code!";

    ?> CORRECT:
    <?php

    echo "Here's my code!";

    /* End of file myfile.php */
    /* Location: ./system/modules/mymodule/myfile.php */


    类和方法(函数)的命名规则
    类名的首字母应该大写。如果名称由多个词组成,词之间要用下划线分隔,不要使用骆驼命名法。类中所有其他方法的名称应该完全小写并且名称能明确指明这个函数的用途,最好用动词开头。尽量避免过长和冗余的名称。
    class Super_class {
        function __construct()
        {
        }
    }

    class Super_class

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


    变量命名
    变量的命名规则与方法的命名规则十分相似。就是说,变量名应该只包含小写字母,用下划线分隔,并且能适当地指明变量的用途和内容。那些短的、无意义的变量名应该只作为迭代器用在for()循环里。

    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
     *
     * @access public
     * @param string
     * @return string
     */
    function xml_encode($str)

    使用行注释时,在大的注释块和代码间留一个空行。

    // break up the string by newlines
    $parts = explode(&quot;\n&quot;, $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-&gt;foo($parts);

     

    常量
    常量命名除了要全部用大写外,其他的规则都和变量相同。在适当的时候,始终使用CodeIgniter常量,例如LASH, LD, RD, PATH_CACHE等等。

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


    TRUE, FALSE, 和 NULL
    TRUE, FALSE, 和 NULL 关键字应该总是完全大写的。

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


    逻辑操作符
    || 有时让人底气不足,因为在某些输出设备上它不够清晰(可能看起来像数字11). && 要优先于 AND 不过两者都可以接受, 在 ! 的前后都要加一个空格。

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

    比较返回值与类型映射
    部分PHP函数执行失败时返回 FALSE, 但也可能有一个有效的返回值 "" 或 0, 它在松散比较中会被计算为FALSE. 在条件语句中使用这些返回值的时候,为了确保返回值是你所预期的类型而不是一个有着松散类型的值,请进行显式的比较。
    在返回和检查你自己的变量时也要遵循这种严格的方法,必要时使用=== 和 !== 。

    if (strpos($str, 'foo') === FALSE)
    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开始标记之前和结束标记之后都不能有空格。输出已经被缓存,所以文件中的空格会导致 CodeIgniter在输出自己的内容之前就开始了输出,这会使CodeIgniter出错且无法输出正确的header。在下面的例子中,使用鼠标选中这些文本,你就能看到那些不应该有的空格。

     

    <?php
        // ...在PHP开始标记上面有空格和换行符
        // 并且在PHP结束标记后面也有空格
    ?> 


    兼容性
    除非你的附加组件的文档中有特别说明,否则所有代码必须与PHP 4.3以上版本兼容。此外,不要使用那些依赖于非默认安装的库的函数,除非你的代码中包含了该函数不可用时的替代方法,或者你在文档中明确说明了你的附加组件需要某些库。

    使用常见词语来命名类和文件
    当你的类或文件名是一个常见词语时,或者是很可能与另一个PHP脚本同名时,使用一个唯一的前缀来避免冲突。你必须始终明白这一点:你的最终用户可能会运行其它第三方的附加组件或者PHP脚本。选择一个能够唯一标识开发者或公司的前缀。

    class Pre_email pi.pre_email.php
    class Pre_xml ext.pre_xml.php
    class Pre_import mod.pre_import.php


    数据库表名
    你的附加组件所用到的任何表都必须使用 'exp_' 这个前缀,然后是一个能够唯一标识开发者或公司的前缀,最后才是一个简短的描述性的表名。你不需要担心用户安装时所使用的数据库前缀,因为 CodeIgniter的数据库类将根据实际情况自动地对 'exp_' 进行转换。

    exp_pre_email_addresses

    一个文件一个类
    对于你的附加组件所使用的类应当遵循一个文件一个类的原则,除非这些类是紧密相关的。CodeIgniter的文件中包含多个类的一个例子是数据库类文件,其中包含了DB类和DB_Cache类,还有Magpie插件,其中包含了Magpie和Snoopy类。

    空格
    在代码中使用tab代替空格。这虽然看起来像是小事,但是使用tab代替空格有利于那些阅读你的代码的开发者在他们各自所使用的应用程序中自定义缩进方式。此外还有一个好处是,使用这种方式保存的文件稍微紧凑一点。

    换行
    文件必须使用Unix换行符保存。这对于那些在Windows下的开发者来说更为重要,但无论如何,确保你的文本编辑器已经设置为使用Unix换行符来保存文件。

    代码缩进
    使用 Allman 风格缩进。除了类声明以外,括号总是独占一行,且缩进与“属于”它的控制语句同级。
    function foo($bar)
    {
        // ...
    }

    foreach ($arr as $key =&gt; $val)
    {
        // ...
    }

    if ($foo == $bar)
    {
        // ...
    }
    else
    {
        // ...
    }

    for ($i = 0; $i &lt; 10; $i++)
    {
        for ($j = 0; $j &lt; 10; $j++)
        {
            // ...
        }
    }


    Bracket and Parenthetic Spacing
    In general, parenthesis and brackets should not use any additional spaces. The exception is that a space should always follow PHP control structures that accept arguments with parenthesis (declare, do-while, elseif, for, foreach, if, switch, while), to help distinguish them from functions and increase readability.

    $arr[$foo] = 'foo'; // no spaces around array keys
    function foo($bar) // no spaces around parenthesis in function declarations
    {

    }

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

    Localized Text
    Any text that is output in the control panel should use language variables in your lang file to allow localization.

    INCORRECT:
    return "Invalid Selection";
    CORRECT:
    return $this->lang->line('invalid_selection');

      
    Private Methods and Variables
    Methods and variables that are only accessed internally by your class, such as utility and helper functions that your public methods use for code abstraction, should be prefixed with an underscore.

    convert_text() // public method
    _convert_text() // private method

    PHP Errors
    Code must run error free and not rely on warnings and notices to be hidden to meet this requirement. For instance, never access a variable that you did not set yourself (such as $_POST array keys) without first checking to see that it isset().
    Make sure that while developing your add-on, error reporting is enabled for ALL users, and that display_errors is enabled in the PHP environment. You can check this setting with:

    if (ini_get('display_errors') == 1)
    {
    exit "Enabled";
    }
    On some servers where display_errors is disabled, and you do not have the ability to change this in the php.ini, you can often enable it with:

    ini_set('display_errors', 1);

    NOTE: Setting the display_errors setting with ini_set() at runtime is not identical to having it enabled in the PHP environment. Namely, it will not have any effect if the script has fatal errors

    Short Open Tags
    Always use full PHP opening tags, in case a server does not have short_open_tag enabled.

    INCORRECT:
    <? echo $foo; ?>
    <?=$foo?>
    CORRECT:
    <?php echo $foo; ?>

    One Statement Per Line
    Never combine statements on one line.
    INCORRECT:
    $foo = 'this'; $bar = 'that'; $bat = str_replace($foo, $bar, $bag);
    CORRECT:
    $foo = 'this';
    $bar = 'that';
    $bat = str_replace($foo, $bar, $bag);

    Strings
    Always use single quoted strings unless you need variables parsed, and in cases where you do need variables parsed, use braces to prevent greedy token parsing. You may also use double-quoted strings if the string contains single quotes, so you do not have to use escape characters.
    INCORRECT:
    "My String"    // no variable parsing, so no use for double quotes
    "My string $foo"    // needs braces
    'SELECT foo FROM bar WHERE baz = \'bag\''    // ugly
    CORRECT:
    'My String'
    "My string {$foo}"
    "SELECT foo FROM bar WHERE baz = 'bag'"


    SQL Queries
    MySQL keywords are always capitalized: SELECT, INSERT, UPDATE, WHERE, AS, JOIN, ON, IN, etc.
    Break up long queries into multiple lines for legibility, preferably breaking for each clause.

    INCORRECT :
    // 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");
    CORRECT :
    $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");

    Default Function Arguments
    Whenever appropriate, provide function argument defaults, which helps prevent PHP errors with mistaken calls and provides common fallback values which can save a few lines of code. Example:
    function foo($bar = '', $baz = FALSE)

  • 相关阅读:
    微信小程序开发前期准备
    怎样在vs2013和vs2015中实现自动编译sass
    在MVC中使用Bundle打包压缩js和css
    Html5 突破微信限制实现大文件分割上传
    Automapper 实现自动映射
    Polly一种.NET弹性和瞬态故障处理库(重试策略、断路器、超时、隔板隔离、缓存、回退、策略包装)
    关于transactionscope 事务的脏数据
    IIS设置session时长
    已禁用对分布式事务管理器(MSDTC)的网络访问的解决方法之一
    DAL.SQLHelper 的类型初始值设定项引发异常的处理
  • 原文地址:https://www.cnblogs.com/holyes/p/222bac5751b250afeb807f0eac0781a4.html
Copyright © 2020-2023  润新知