Комментирование кода. Стандарт Doxygen



Doxygen — это система генерации документации. Документация извлекается прямо из источников, что делает более лёгким хранение документации вместе с исходным кодом

На сайте Doxygen находится замечательное руководство по этой системе. Следующие рекомендации имеют отношению к работе с Doxygen в Drupal.

Основной синтаксис документов

Чтобы документировать блок определённого кода, используется следующий синтаксис:

/**
* Documentation here.
*/

Doxygen поймёт любые комментарии расположенные в таком блоке. Ваш стиль должен содержать по возможности команды стандартные для Doxygen, таким образом мы сохраняем источник чётким. Любые упоминания функций или названий файлов в документации, автоматически создадут ссылки на тот код, на который они ссылаются.

Документирование файлов

Хорошая практика — это описать что делает файл уже в самом начале.

<?php
// $Id: theme.inc,v 1.202 2004/07/08 16:08:21 dries Exp $

/**
* @file
* The theme system, which controls the output of Drupal.
*
* The theme system allows for nearly all output of the Drupal system to be
* customized by user themes.
*/

The line immediately following the @file directive is a short description that will be shown in the list of all files in the generated documentation. If the line begins with a verb, that verb should be in present tense, e.g., "Handles file uploads." Further description may follow after a blank line.

Чтобы CVS могла работать с вашими файлами, добавляйте в начало файлов тег // $Id$. CVS автоматически заполнит этот тег актуальной информацией и ван не нужно будет беспокоиться об обновлении этой записи вручную.

Документирование функций

Все функции, которые могут быть вызваны другими файлами, должны быть документированы; локальные функции тоже желательно документировать. Блок комментирования функции должен ей непосредственно предшествовать.

/**
* Verify the syntax of the given e-mail address.
*
* Empty e-mail addresses are allowed. See RFC 2822 for details.
*
* @param $mail
*   A string containing an email address.
* @return
*   TRUE if the address is in a valid format.
*/
function valid_email_address($mail) {

The first line of the block should contain a brief description of what the function does, beginning with a verb in the form "Do such and such" (rather than "Does such and such"). A longer description with usage notes may follow after a blank line. Each parameter should be listed with a @param directive, with a description indented on the following line. After all the parameters, a @return directive should be used to document the return value if there is one. There is no blank line between the @param and @return directives. Functions that are easily described in one line may omit these directives, as follows:

/**
* Convert an associative array to an anonymous object.
*/
function array2object($array) {

The parameters and return value must be described within this one-line description in this case.

Комментирование hook'ов

Многие модули содержат большое количество выполняемых hook'ов. Если выполнение достаточно стандартно и не требует дополнительного объяснения, то для описания hook'а может использоваться короткое описание.

/**
* Implementation of hook_help().
*/
function blog_help($section) {

Этот комментарий сгенерирует ссылку на описание hook'а, напомнив разработчику, что этот hook выполняет и позволит избежать комментирование параметров каждый раз, вернув значение комментария которое одинаково для одного и того же hook'а.

Комментирование форм

In order to provide a quick reference for themers, we tag all form builder functions so that Doxygen can group them together. The form builder function is defined as any function meant to be used as an argument for drupal_get_form. To do this, add a grouping instruction to the documentation of the function. Additionally, while submit, validate and other handlers for the form are not meant to be in this group, you should provide a @see to provide an easy reference to handlers that are attached to the form.

/**
* FAPI definition for the user login form.
*
* ...
* @ingroup forms
* @see user_login_default_validators()
* @see user_login_submit()
*/
function user_login(&$form_state, $msg = '')

Комментирование функций оформления

In order to provide a quick reference for theme developers, we tag all themeable functions so that Doxygen can group them on one page. To do this, add a grouping instruction to the documentation of all such functions:

/**
* Format a query pager.
*
* ...
* @ingroup themeable
*/
function theme_pager($tags = array(), $limit = 10, $element = 0, $attributes = array()) {
  ...
}

Комментирование шаблонов тем

If a template and a preprocess function is used instead of a theming function, an empty function definition of the theme function that is not used should be placed in the contributed documentation (contributions/docs/developer/theme.php).

The template itself should be documented with a @file directive and contain a list of the variables that the template_preprocess_HOOK has prepared for it. If any of these variables contain data that is unsafe to output for XSS reasons, they should be documented; otherwise it can be assumed that variables available have already been appropriately filtered. Anything not listed should not be assumed to be safe to output. It should also contain a @see directive to link back to the preprocessor and the theme_X function.

<?php
// $Id$

/**
* @file forum_list.tpl.php
* Default theme implementation to display a list of forums.
*
* Available variables:
* - $forums: An array of forums to display.
*
* Each $forum in $forums contains:
* - $forum->is_container: Is TRUE if the forum can contain other forums. Is
*   FALSE if the forum can contain only topics.
* - $forum->depth: How deep the forum is in the current hierarchy.
* - $forum->name: The name of the forum.
* - $forum->link: The URL to link to this forum.
* - $forum->description: The description of this forum.
* - $forum->new_topics: True if the forum contains unread posts.
* - $forum->new_url: A URL to the forum's unread posts.
* - $forum->new_text: Text for the above URL which tells how many new posts.
* - $forum->old_topics: A count of posts that have already been read.
* - $forum->num_posts: The total number of posts in the forum.
* - $forum->last_reply: Text representing the last time a forum was posted
*   or commented in.
*
* @see template_preprocess_forum_list()
*/

The template_preprocess_HOOK function should also contain appropriate @see directives.

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
Image CAPTCHA
Copy the characters (respecting upper/lower case) from the image.