PHPDoc에서 어레이 옵션을 문서화하는 가장 좋은 방법
함수에 전달되는 어레이 옵션의 멀티 트리 구조를 설명하는 읽기 쉽고 이해하기 쉬운 문서를 작성하는 데 어려움을 겪고 있습니다.
다음은 어레이 구조의 예입니다.
$arr = [
'fields' => [
'title' => [
'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 문서가 생성되었을 때 포맷이 잘 되지 않는 것이 문제입니다.또, 상기의 어레이 구조가 명확하게 설명되고 있는 것은 아닙니다.
다른 방법이 있나요?
대신 이렇게 합니다.
/**
* 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
그래야 한다.
다음과 같은 키를 지정할 수 있는 phpstorm용 플러그인을 작성했습니다.
(@siannone 포맷의 조금 더 정형화된 버전만 포함)
/**
* @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][''];
}
이 명령어를 사용하면@return
키도 마찬가지입니다.
/**
* @return array [
* 'success' => true,
* 'formObject' => new Form,
* 'errors' => [],
* ]
*/
public static function processForm($arr);
널리 받아들여지고 있는 키 타입의 문서 형식 중에서, 여기에서는 몇개의 인기 있는 것을 언급하고 싶습니다.
시편/PHPStan/판 형식
/** @param array{foo: string, bar: int} $args */
보너스로, 툴로 정적 코드 분석에도 사용할 수 있습니다.
워드프레스 형식
/**
* @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.
* }
*/
둘 다 딥 어소션 플러그인으로 지원됩니다.
표를 추가하는 것만으로 보기 쉽고 알기 쉽게 할 수 있습니다.
/**
* 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 ['array [' fields ' ]array ]으로합니다.
- [fieldName] 배열 필드에 대한 옵션을 정의하거나 배열이 적용되지 않은 경우 필드만 활성화합니다.
- ['name'] 문자열 필드 이름을 덮어씁니다(기본값은 배열 키).
- ['model'] 문자열(선택사항) 필드가 연결된 값인 경우 모델을 재정의합니다.
- ['width'] 문자열 페이지 단위 보기에 대한 필드 너비를 정의합니다.예: "100px" 또는 "auto"
- ['align'] 페이지 단위 뷰에 대한 문자열 정렬 유형(왼쪽, 오른쪽, 가운데)
- ['format'] 문자열 페이지 번호 필드에 대한 형식 지정 옵션입니다.옵션에는 ('통화', 'nice', 'niceShort', 'timeAgoInWords' 또는 유효한 Date() 형식이 포함됩니다.)
- ['title'] 문자열 보기에 표시되는 필드 이름을 변경합니다.
- ['desc'] string 편집/작성 뷰에 표시되는 설명입니다.
- ['read only'] boolean True는 사용자가 편집/작성 양식의 값을 변경할 수 없도록 합니다.
- ['type'] 문자열 Form 도우미가 사용하는 입력 유형을 정의합니다(예: 'password').
- ['options']어레이 드롭다운목록에 대한 문자열 옵션 목록을 정의합니다.
- ['editor'] boolean True로 설정하면 이 필드에 대한 WYSIWYG 편집기가 표시됩니다.
- ['default'] 문자열 생성 양식의 기본값입니다.
- [fieldName] 배열 필드에 대한 옵션을 정의하거나 배열이 적용되지 않은 경우 필드만 활성화합니다.
화려하게 연출하고 싶다면 약간의 CSS로 경이로운 연출을 할 수 있습니다.xd
어레이 대신 객체를 사용할 수 있습니까?그러면 서류작업이 쉬워집니다.
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) {...}
Markdown Syntax for Object Notation(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
*/
난 이게 더 좋아
* @param array $doc
* 'type'=>Doc::MY_DOC_TYPE,
* 'created'=>$now,
* 'modified'=>$now
초기화된 코드부터 빠르고 쉽게 붙여넣기만 하면 됩니다.
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에서 훔쳐서 후유증을 만들어내거나...
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;
}
이러한 3가지 옵션 중 어느 것이 기능할지 여부는 사용하는 툴에 따라 달라집니다.
그럼 거짓말...
/** @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;
}
문제는 어레이를 개체로 변환한다는 것입니다.퍼포먼스에 미치는 영향과 변경은 모두 참조용으로 값별로 전달됩니다.어느 쪽이 빠른지는 논란의 여지가 있다.어레이는 이론적으로 더 빨라야 하지만 오브젝트는 기본적으로 참조라는 이점이 있고 PHP와 달리 오브젝트와 어레이를 분리하는 JSON에서 더 잘 작동합니다.
내의 힌트에 잘되지 않을 수 있는 PHP를 사용).->{key}
[key]
한 일이 다른 이상한 일이 일어날 가능성이 있습니다.
퍼포먼스가 정말 중요한 경우 PHP를 컴파일 언어로 변경할 수 있습니다.같은 방법으로 인터페이스를 확장하여 오브젝트를 컴파일 가능한 상태로 만들 수 있습니다.OOP 및 자동 완료를 사용하여 모든 작업을 수행할 수 있지만, 랩된 속성을 지정한 후 reflection을 사용하여 일치 메서드의 내용으로 대체하고 몇 개의 확장자를 사용하여 클래스를 인라인화하는 것과 동등한 작업을 수행할 수 있습니다.ra bits needed (인라인 또는 프로시저로 변환하는 것, 랩할 단일 속성 또는 다중 속성 등)
그 개념은 복싱과 언박싱과 비슷하다.SA 지원과 IDE(자동 완성, 검사 등), 분석기, 도구 등에 대한 광범위한 지원에 관심이 있다면 이 방법만이 유일한 방법일 수 있습니다.
이것은 지시문이 아니라 순전히 표시이며 문서 내에 공간 서식을 유지해야 하기 때문에, 나는 글자의 벽보다는 들여쓰기로 가독성을 추구하는 경향이 있다.
* 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 어레이 정의를 사용하는 것이 훨씬 더 깨끗합니다.
언급URL : https://stackoverflow.com/questions/15414103/best-way-to-document-array-options-in-phpdoc
'programing' 카테고리의 다른 글
Python의 ISO 시간(ISO 8601) (0) | 2022.11.08 |
---|---|
안드로이드:Dex는 버전 52 바이트 코드를 구문 분석할 수 없습니다. (0) | 2022.11.08 |
dyld: 라이브러리가 로드되지 않음: /usr/local/lib/libpng16.16.dylib (ph 관련 항목 포함) (0) | 2022.11.08 |
iframe과 상위 사이트 간의 통신 방법 (0) | 2022.11.08 |
.lib가 스태틱인지 Import인지 확인합니다. (0) | 2022.11.08 |