13

假设我有一个名为Color的 PHP 类,它的构造函数接受各种参数。

// hex color
$myColor = new Color('#FF008C');

// rgb channels
$myColor = new Color(253,15,82);

// array of rgb channels
$myColor = new Color(array(253,15,82));

// X11 color name
$myColor = new Color('lightGreen');

我应该如何使用 phpDoc 为构造函数和其他类似方法创建 API 文档?

如何使用带有重载方法的phpDoc?

class Color {

    /**
     * Constructor
     * what should be here?
     */
    public function __construct() {
        /* CODE */
    }

}
4

4 回答 4

18

只是我的观点,但首先你不应该有多个构造函数 - 你的构造函数将充满 if/else-ladders,这真的不是一个好主意,特别是对于像一个表示的轻量级的东西颜色。

我强烈建议您尝试这样的事情:

class Color
{
    protected function __construct($r, $g, $b)
    { ... }

    public static function fromHex($hex) {
        return new Color(...);
    }

    public static function fromRGB($r, $g, $b) { ... }

    public static function fromArray(array $rgb) { ... }

    ...
}

现在,在消费者代码中,而不是像这样有点神秘和模棱两可的构造函数调用:

$a = new Color(0,0,0);
$b = new Color('#000000');

相反,您可以拥有更清晰和语义化的消费者代码,如下所示:

$a = Color::fromRGB(0,0,0);
$b = Color::fromHex('#000000');

这可能对阅读消费者代码的人更有意义,它消除了使模棱两可的构造函数工作所需的逻辑,并且作为奖励(如果您使用的是 PhpStorm 之类的 IDE),您可以通过所有检查。如果您正在运行文档生成器,这还可以确保所有选项都单独记录,而不是集中在口头描述中。

请注意,我声明了构造函数protected- 这是个人偏好,但如果我将拥有多个静态工厂方法,我更喜欢看到那些在消费者代码中始终使用的那些,而不是有时看到Color::fromRGB(...)和其他时候new Color(...)

于 2013-06-28T16:11:59.790 回答
8

我认为最好@method为类/接口使用注释,它声明重载方法。这个问题对我来说也很有趣。

 /**
  * @method void setValue(int $value)
  * @method void setValue(string $value)
  * @method void setValue(string $value, int $startFrom)
  */
 class Example
 {
     public function setValue($arg1, $arg2)
     {
        // ...
     }
 }

请参阅http://phpdoc.org/docs/latest/references/phpdoc/tags/method.html

于 2014-02-27T12:20:50.700 回答
4

因为您允许可变长度参数,所以我有两种方法可以做到这一点。

我会简单地列出允许的参数是参数。

/**
 * @param mixed $arg1 ... description
 * @param mixed $arg2 ... description
 * @param mixed $arg3 ... description
 */
 public function __construct() {}

或者我会简单地用一些例子来解释。

/**
 * Explanation of different expected argument combinations.
 */
public function __construct() {}

另一种选择是,由于只有一个示例具有多个参数,因此只需在方法签名中定义参数,使最后 2 个可选。像这样:

/**
 * @param mixed $arg1 ...
 * @param int $arg2 ...
 * @param int $arg3 ...
 */
public function __construct($arg1, $arg2 = null, $arg3 = null) {}
于 2009-08-28T19:33:59.897 回答
1

我知道没有优雅的方法可以用 phpDoc 做到这一点。phpDoc 注释/api 格式基于Javadoc格式。Javadoc 没有功能集来支持这一点,因为在 java 中,如果您希望方法具有可变数量的参数,您需要为每个变体重新声明方法原型。

public double foo() {
}

public double foo(double my_param) {        
}

所以,我的性能偏好是做类似的事情

/**
 * My General description
 * 
 * Here explain what each argument combination can do
 * @param mixed $arg1 can be array, string, hex as string, or int 
 * @param int $arg2 if arg1 is int, then this is etc, otherwise optional 
 * @param int $arg3 if ar1 is int, then this is etc, otherwise optional
 */

但这可能不适用于各种自动文档工具。

可以在phpDoc 站点上找到按照 Hoyle 的方法来完成此操作。

于 2009-08-28T19:50:32.903 回答