在PHPDoc中记录数组选项的最佳方法?

时间:2013-03-14 15:56:58

标签: php cakephp phpdoc

我正在努力编写可读且易于理解的文档,这些文档描述了传递给函数的Array选项的多树结构。

这是一个示例数组结构。

$arr = array(
   'fields'=>array(
       'title'=>array('name'=>'Document.title','format'=>'string','readonly'=>true)
   )
);

上述数组有许多可能的选项,但这用作理解该结构的函数的参数。

function doSomething(array $arr) {...}

我想记录如何在PHPDoc中构建数组,但我不确定正确的方法是什么。

这就是我现在所拥有的。

/**
 * Holds configuration settings for each field in a model.
 * Defining the field options
 *
 * array['fields'] array Defines the feilds to be shown by scaffolding.
 * array['fields'][fieldName] array Defines the options for a field, or just enables the field if array is not applied.
 * array['fields'][fieldName]['name'] string Overrides the field name (default is the array key)
 * array['fields'][fieldName]['model'] string (optional) Overrides the model if the field is a belongsTo assoicated value.
 * array['fields'][fieldName]['width'] string Defines the width of the field for paginate views. Examples are "100px" or "auto"
 * array['fields'][fieldName]['align'] string Alignment types for paginate views (left, right, center)
 * array['fields'][fieldName]['format'] string Formatting options for paginate fields. Options include ('currency','nice','niceShort','timeAgoInWords' or a valid Date() format)
 * array['fields'][fieldName]['title'] string Changes the field name shown in views.
 * array['fields'][fieldName]['desc'] string The description shown in edit/create views.
 * array['fields'][fieldName]['readonly'] boolean True prevents users from changing the value in edit/create forms.
 * array['fields'][fieldName]['type'] string Defines the input type used by the Form helper (example 'password')
 * array['fields'][fieldName]['options'] array Defines a list of string options for drop down lists.
 * array['fields'][fieldName]['editor'] boolean If set to True will show a WYSIWYG editor for this field.
 * array['fields'][fieldName]['default'] string The default value for create forms.
 *
 * @param array $arr (See above)
 * @return Object A new editor object.
 **/

我的问题是,当生成HTML文档时,它的格式不是很好。另外,我不确定上面是否清楚地解释了阵列结构。

有替代方法吗?

9 个答案:

答案 0 :(得分:46)

派对有点太晚了,但这就是我这样做的方式:

/**
 * Class constructor.
 *
 * @param array $params Array containing the necessary params.
 *    $params = [
 *      'hostname'     => (string) DB hostname. Required.
 *      'databaseName' => (string) DB name. Required.
 *      'username'     => (string) DB username. Required.
 *      'password'     => (string) DB password. Required.
 *      'port'         => (int) DB port. Default: 1433.
 *      'sublevel'     => [
 *          'key' => (\stdClass) Value description.
 *      ]
 *    ]
 */
 public function __construct(array $params){}

认为它非常干净且易于理解$params应该是什么。

答案 1 :(得分:31)

只需添加一些列表即可使其看起来更好且易于理解

/**
 * Holds configuration settings for each field in a model.
 * Defining the field options
 *
 * array['fields']              array Defines the fields to be shown by scaffolding.
 *          [fieldName]         array Defines the options for a field, or just enables the field if array is not applied.
 *              ['name']        string Overrides the field name (default is the array key)
 *              ['model']       string (optional) Overrides the model if the field is a belongsTo associated value.
 *              ['width']       string Defines the width of the field for paginate views. Examples are "100px" or "auto"
 *              ['align']       string Alignment types for paginate views (left, right, center)
 *              ['format']      string Formatting options for paginate fields. Options include ('currency','nice','niceShort','timeAgoInWords' or a valid Date() format)
 *              ['title']       string Changes the field name shown in views.
 *              ['desc']        string The description shown in edit/create views.
 *              ['readonly']    boolean True prevents users from changing the value in edit/create forms.
 *              ['type']        string Defines the input type used by the Form helper (example 'password')
 *              ['options']     array Defines a list of string options for drop down lists.
 *              ['editor']      boolean If set to True will show a WYSIWYG editor for this field.
 *              ['default']     string The default value for create forms.
 *
 * @param array $arr (See above)
 * @return Object A new editor object.
 **/

嵌套列表方法:

<ul>
    <li>
        array['fields'] array Defines the fields to be shown by scaffolding.
        <ul>
            <li>
                [fieldName]             array Defines the options for a field, or just enables the field if array is not applied.
                <ul>
                    <li> ['name']       <i><u>string</u></i> Overrides the field name (default is the array key) </li>
                    <li> ['model']      <i><u>string</u></i> (optional) Overrides the model if the field is a belongsTo associated value.</li>
                    <li> ['width']      <i><u>string</u></i> Defines the width of the field for paginate views. Examples are "100px" or "auto"</li>
                    <li> ['align']      <i><u>string</u></i> Alignment types for paginate views (left, right, center)</li>
                    <li> ['format']     <i><u>string</u></i> Formatting options for paginate fields. Options include ('currency','nice','niceShort','timeAgoInWords' or a valid Date() format)</li>
                    <li> ['title']      <i><u>string</u></i> Changes the field name shown in views.</li>
                    <li> ['desc']       <i><u>string</u></i> The description shown in edit/create views.</li>
                    <li> ['readonly']   <i><u>boolean</u></i> True prevents users from changing the value in edit/create forms.</li>
                    <li> ['type']       <i><u>string</u></i> Defines the input type used by the Form helper (example 'password')</li>
                    <li> ['options']    <i><u>array</u></i> Defines a list of string options for drop down lists.</li>
                    <li> ['editor']     <i><u>boolean</u></i> If set to True will show a WYSIWYG editor for this field.</li>
                    <li> ['default']    <i><u>string</u></i> The default value for create forms.</li>
                </ul>
            </li>
        </ul>
    </li>
 </ul>

结果:

        
  •         array ['fields'] array定义脚手架显示的字段。         
                  
    •                 [fieldName] array定义字段的选项,或者仅在未应用数组时启用字段。                 
                            
      • ['name'] string 覆盖字段名称(默认为数组键)
      •                     
      • ['model'] string (可选)如果字段是belongsTo关联值,则覆盖模型。
      •                     
      • ['width'] string 定义分页视图的字段宽度。例如“100px”或“auto”
      •                     
      • ['align'] string 分页视图的对齐类型(左,右,中)
      •                     
      • ['format'] string 分页字段的格式选项。选项包括('currency','nice','niceShort','timeAgoInWords'或有效的Date()格式)
      •                     
      • ['title'] string 更改视图中显示的字段名称。
      •                     
      • ['desc'] string 编辑/创建视图中显示的说明。
      •                     
      • ['readonly'] boolean True可防止用户更改编辑/创建表单中的值。
      •                     
      • ['type'] string 定义表单助手使用的输入类型(示例'密码')
      •                     
      • ['options'] array 定义下拉列表的字符串选项列表。
      •                     
      • ['editor'] boolean 如果设置为True,则会显示该字段的WYSIWYG编辑器。
      •                     
      • ['default'] string 创建表单的默认值。
  •      

如果你想要它看起来很花哨,有点Css它会创造奇迹! XD

答案 2 :(得分:23)

您可以使用对象而不是数组吗?这将使文档变得容易。

class Field {

    /**
     * The name of the thing.
     * @var string
     */
    protected $name;

    protected $model;
    protected $width;
    //...

    public function getName() {...}
    public function setName() {...}
    //...
}

class FieldList implements SomeKindOfIterator {

    /**
     * Some fields.
     * @var Field[]
     */
    protected $fields = array();

    /**
     * ...
     */
    public function push(Field $field) {
         $this->fields[] = $field;
    }

    //...
}

然后您可以使用需要该类的类型提示。

/**
 * Do something.
 * @param FieldList $field_list The field.
 */
function doSomething(FieldList $field_list) {...}

答案 3 :(得分:22)

我写了一个plugin for phpstorm,它允许指定这样的键:

/**
 * @param array $arr = [
 *     'fields' => [ // Defines the feilds to be shown by scaffolding
 *         $anyKey => [
 *             'name' => 'sale', // Overrides the field name (default is the array key)
 *             'model' => 'customer', // (optional) Overrides the model if the field is a belongsTo associated value.
 *             'width' => '100px', // Defines the width of the field for paginate views. Examples are "100px" or "auto"
 *             'align' => 'center', // Alignment types for paginate views (left, right, center)
 *             'format' => 'nice', // Formatting options for paginate fields. Options include ('currency','nice','niceShort','timeAgoInWords' or a valid Date() format)
 *             'title' => 'Sale', // Changes the field name shown in views.
 *             'desc' => 'A deal another person that results in money', // The description shown in edit/create views.
 *             'readonly' => false, // True prevents users from changing the value in edit/create forms.
 *             'type' => 'password', // Defines the input type used by the Form helper
 *             'options' => ['option1', 'option2'], // Defines a list of string options for drop down lists.
 *             'editor' => false, // If set to True will show a WYSIWYG editor for this field.
 *             'default' => '', // The default value for create forms.
 *         ],
 *     ],
 * ]
 */
public static function processForm($arr)
{
    $fieldName = 'sale';
    $arr['fields'][$fieldName][''];
}

enter image description here

它还可以指定@return键:

/**
 * @return array [
 *     'success' => true,
 *     'formObject' => new Form,
 *     'errors' => [],
 * ]
 */
public static function processForm($arr);

enter image description here

答案 4 :(得分:9)

在广泛接受的密钥类型文档格式中,我想在这里提及一些流行的格式:

Psalm / PHPStan / phan格式

/** @param array{foo: string, bar: int} $args */

作为奖励,也可以用于static code analysis及其工具

Wordpress格式

/**
 * @param array $args {
 *     Optional. An array of arguments.
 *
 *     @type type $key Description. Default 'value'. Accepts 'value', 'value'.
 *                     (aligned with Description, if wraps to a new line)
 *     @type type $key Description.
 * }
 */

deep-assoc-completion插件

都支持

答案 5 :(得分:8)

http://localhost:8080/profile,and(MSON)可能是更好的选择。

例如

/**
 * @param array $config
 *   + app (string, required) - app directory name
 *   + view (string, required) - view directory name
 *   + type (enum[string]) - site type
 *     + pc - PC version
 *     + wap - mobile version
 *     + other - other, default value
 *   + table_prefix (string) - database table prefix
 */

答案 6 :(得分:3)

我更喜欢这样:

 * @param array $doc
 *          'type'=>Doc::MY_DOC_TYPE,
 *          'created'=>$now,
 *          'modified'=>$now

我只需粘贴初始化的代码,快速简便。

答案 7 :(得分:1)

由于这纯粹是显示而不是指令,并且应该在文档中保留空格格式,我倾向于使用缩进而不是字符墙来提高可读性:

 * array['fields'] array Defines the feilds to be shown by scaffolding.
 *           [fieldName] array Defines the options for a field, or just enables
 *                             the field if array is not applied.
 *                 ['name'] string Overrides the field name (default is the
 *                                  array key)
 *                 ['model'] string (optional) Overrides the model if the field is
 *                                  a belongsTo assoicated value.
 *                 ['width'] string Defines the width of the field for paginate
 *                                  views.
 *                                  Examples are "100px" or "auto"
 *                 ['align'] string Alignment types for paginate views (left, 
 *                                 right, center)
 *                 ['format'] string Formatting options for paginate fields.
 *                                   Options include 'currency', 'nice',
 *                                  'niceShort', 'timeAgoInWords' or a valid 
 *                                  Date() format)
 *                 ['title'] string Changes the field name shown in views.
 *                 ['desc'] string The description shown in edit/create views.
 *                 ['readonly'] boolean True prevents users from changing the
 *                                 value in edit/create forms.
 *                 ['type'] string Defines the input type used by the Form helper
 *                                  (example 'password')
 *                 ['options'] array Defines a list of string options for drop-
 *                                  down lists.
 *                 ['editor'] boolean If set to True will show a WYSIWYG editor
 *                                  for this field.
 *                 ['default'] string The default value for create forms.

虽然使用带缩进的实际PHP数组定义更加清晰

答案 8 :(得分:0)

PHP中的数组实际上更像是匿名结构。

对于任意数据结构,有许多模式验证器,但不幸的是,类型提示未广泛支持它。也许一些常见的方案有插件?问题是事物只能在一个或几个地方工作。您可能会为自己的IDE工作正常,但要运行静态分析,一切都会陷入困境。

需要格外小心,以将事物分开,以便在可能的情况下,其他不支持方案的工具(例如通过插件)将完全忽略它。

PHPDoc倾向于在任何地方都受支持,但也非常有限。

经常有提议,但是没有真正的好标准。大多数解决方案都是非标准的,未得到广泛支持的,具有局限性或纯属肤浅(文档)的部分黑客。

在特定位置有特定的实现,但是没有广泛的应用和专用于PHP本身。尽管您可以在PHP IDE中创建自己的模式,但往往缺少像样的代码桥,即使是那些以PHP为名的代码桥。

您应该单独定义字段结构。您的外部数据结构是伪代码@key fields field[],而不是多维数组。从概念上和令人困惑的角度,您可以进行以下操作:

@start struct custom
@key \stdClass *
@end struct

@start struct fields
@key string hostname
@key string databaseName
@key string password
@key int port=1433
@key custom|undefined sublevel
@end struct

@start struct connection
@key fields fields
@end struct

或者从C那里窃取,然后发明一个Laguage ...

struct connection {
    struct fields {
        string hostname;
        string databaseName;
        string password;
        int port = 1433;
        custom optional sublevel {
            stdClass *;
        };
    };
};

您可以发明基于结构的架构,以允许平面和嵌套。嵌套应为默认值,仅应将事物定义为可重用。

一种不寻常的方法是改为使用对象。不必使用诸如数组访问之类的接口。在PHP中,对象包装了属性数组。可以将数组转换为对象(没有实现,只有属性)然后返回。

如果您使用对象代替关联数组($ array [$ key]与$ object-> {$ key}),则可以使虚拟对象至少欺骗IDE ...

final class PersonStruct {
    /** @var int */
    public $x;

    /** @var int $y */

    public int $z;
}

这三个选项可能有效或无效取决于所使用的工具。

然后您可以撒谎...

/** @var PersonStruct $ps */
$ps = (object)['x' => 0, 'y' => 1, 'z' => 2];

/**
 * @param PersonStruct $ps
 * @return PersonStruct
 */
function f(object $ps):object {
    return $ps;
}

/**
 * @param PersonStruct $ps
 * @return PersonStruct
 */
function f(stdClass $ps):stdClass {
    return $ps;
}

问题是这意味着将数组转换为对象。既影响性能,又影响更改,值传递到引用传递。哪个更快是值得商bat的。从理论上讲,数组应该更快,尽管默认情况下对象具有作为引用的好处,并且可以与JSON更好地结合使用,JSON将对象与数组分开,这与PHP不同。

即使对象中的属性只是一个PHP数组(使用->{key}而不是[key]),对象也不支持在类型提示方面可能设置得不太好的属性。 。还有其他怪异事物的可能性。

如果真正关心性能,则可以将PHP转换为编译语言。以相同的方式,您可以扩展接口以使对象可编译,您可以针对可能使用OOP和自动完成功能进行的所有操作执行相同的操作,但是随后可以通过指定要包装的属性来进行内联类的等效操作,然后使用反映出使用匹配方法的内容进行大量替换的情况,还需要一些额外的位(标记要内联或转换为过程的内容,将单个属性包装或多个,等等)。

该概念类似于装箱和拆箱。如果您真的对SA支持和对IDE(自动完成,检查等),分析器,工具等的广泛支持感到疯狂,那么这可能是唯一的方法。