Skip to content

Symfony 编码规范 #67

Description

@huliuqing

Symfony 编码规范

本文是对 Symfony Coding Standards 一文的翻译

当你想向 Symfony 贡献代码时,编码规范的指导方针,就是模仿 Symfony 的代码风格 进行编码。超多开源软件开发者和本项目使用者都在遵循 Symfony 的编码风格,你也应当遵循它。

谨记,拥有统一标准的编码风格,可以使不同项目,不同代码看起来风格统一;此外,统一编码风格也能提升代码可读性。

Symfony 项目遵循 PSR 编码规范 PSR-0, PSR-1, PSR-2, PSR-4 相关定义。

一图胜千言,以代码实例能达到自描述编码规范的神奇效果

<?php

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

/**
 * Coding standards demonstration.
 */
class FooBar
{
    const SOME_CONST = 42;

    /**
     * @var string
     */
    private $fooBar;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this->fooBar = $this->transformText($dummy);
    }

    /**
     * @return string
     *
     * @deprecated
     */
    public function someDeprecatedMethod()
    {
        @trigger_error(sprintf('The %s() method is deprecated since version 2.8 and will be removed in 3.0. Use Acme\Baz::someMethod() instead.', __METHOD__), E_USER_DEPRECATED);

        return Baz::someMethod();
    }

    /**
     * Transforms the input given as first argument.
     *
     * @param bool|string $dummy   Some argument description
     * @param array       $options An options collection to be used within the transformation
     *
     * @return string|null The transformed input
     *
     * @throws \RuntimeException When an invalid option is provided
     */
    private function transformText($dummy, array $options = array())
    {
        $defaultOptions = array(
            'some_default' => 'values',
            'another_default' => 'more values',
        );

        foreach ($options as $option) {
            if (!in_array($option, $defaultOptions)) {
                throw new \RuntimeException(sprintf('Unrecognized option "%s"', $option));
            }
        }

        $mergedOptions = array_merge(
            $defaultOptions,
            $options
        );

        if (true === $dummy) {
            return null;
        }

        if ('string' === $dummy) {
            if ('values' === $mergedOptions['some_default']) {
                return substr($dummy, 0, 5);
            }

            return ucwords($dummy);
        }
    }

    /**
     * Performs some basic check for a given value.
     *
     * @param mixed $value     Some value to check against
     * @param bool  $theSwitch Some switch to control the method's flow
     *
     * @return bool|void The resultant check if $theSwitch isn't false, void otherwise
     */
    private function reverseBoolean($value = null, $theSwitch = false)
    {
        if (!$theSwitch) {
            return;
        }

        return !$value;
    }
}

结构规范

  • 在逗号 , 分隔符后加入一个空格字符
  • 在二元运算符( ==, &&, ... etc )前后加入一个空格字符,避免连接操作符 . 错误
  • 一元操作符( !, --, ... ) 与变量间不要有空格字符
  • TODO Always use identical comparison unless you need type juggling;
  • 使用尤达条件式,避免意外的复制操作,这适用于 ==, !=, === 和 !==
  • 对于多行的数组元素,这包括最后一个数组元素在内的每个元素后加上逗号 , 分隔符
  • 所有 return 语句前 必须 添加一行空行,但如果语法块内仅有一条 return 语句则不需要加入空行,如例子中的 if 语句
  • 当函数需要返回 null 值时,使用 return null;;如果函数需要返回 void 空值,直接使用 return;
  • 无论控制语句内有到少行代码,务必将代码写入花括号内
  • 类独占一个文件 - this does not apply to private helper classes that are not intended to be instantiated from the outside and thus are not concerned by the PSR-0 and PSR-4 autoload standards;
  • 类的 extends (继承) 和 implements (实现) 必须 与类名写在同一行
  • 类的属性定义 必须 定义在类方法前
  • public 访问权限的方法和属性必须最先定义,紧接着定义 protected 访问权限的方法和属性,最后定义 private 访问权限的方法和属性。但这不适用于类的构造函数,PHPUnit 测试的 setUp()tearDown() 方法,及任何需要提升代码可读性的方法定义
  • 方法或函数中无论参数个数多少,应该 定义在同一行
  • 类实例化时,必须加入括号,无论有有无参数
  • Exception 和 Error 消息内容,必须 使用 sprintf 函数格式化
  • 当调用 trigger_error() 函数触发 E_USER_DEPRECATED 级别错误消息时,必须 在函数前加上错误抑制操作符 @详情请阅读
  • 如需在 ifcase 控制语句后返回数据或抛出异常,不要 使用 else, elseif, break
  • Do not use spaces around [ offset accessor and before ] offset accessor. 属性或方法访问时,不要 加入前后空格($this->transformText($dummy))

命名规范

  • 变量,方法,函数及参数名,必须 使用驼峰命名法( camelCase),而不是下划线命名法(under_scrore)
  • 配置文件中的配置选项和属性使用 下划线命名法(unser_score)
  • 所有的类文件 必须 定义命名空间
  • 抽象类 必须 加上 Abstract 前缀。早期的 Symfony 抽象类并未遵守这个规范,但是所有新加入的抽象类都尊系该规范
  • 接口 必须 加上 Interface 后缀
  • 所有 Traits 必须 加上 Trait 后缀
  • 文件名 必须 使用字符和下划线命名
  • 使用 PHPDoc 文档工具时,使用 bool 而不是 Booleanbooleanint 而不是 integerIntegerfloat 而不是 doublereal
  • 阅读更多关于 Conventions 文档 的内容

Service Naming Conventions

  • A service name contains groups, separated by dots;
  • The DI alias of the bundle is the first group (e.g. fos_user);
  • Use lowercase letters for service and parameter names (except when referring to environment variables with the %env(VARIABLE_NAME)% syntax);
  • A group name uses the underscore notation.

文档规范

  • 所有的类、方法和函数 必须 加上 PHPDoc 注释
  • 相同类型的注释在一个注释组,不同类型的注释以空行分隔
  • 无返回值的方法或函数省略 @return 注释
  • @Package@subpackage 注释块 非必须

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions