Комментирование кода. Стандарт 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.
Documenting contributed modules and themes
- Don't use
@mainpage. There can be only one@mainpagein the contributions repository, which is reserved for an index page of all contributes modules and themes. - Use Doxygen Modules (
@defgroup,@ingroup,@addtogroup, see "Limitations and hints" below) sparingly. There are currently over 2,200 module directories in contrib, many of them consisting of more than one module. If any of these modules uses only one@defgroup, there are more than 2,200 entries in the global Module list. If it uses more than one ... - If you use Doxygen Modules, make sure you give them a unique namespace, which would be your module's name. E.g.
@defgroup views ...for the views.module,@defgroup views_ui ...for the views_ui.module. Don't use group names which are defined in Drupal core (hooks, themeable, file, batch, database, forms, form_api, format, image, validation, search, etc.).
A recommended way of using Doxygen grouping in contributed modules and themes is the following:
in your main example.module:
/**
* @defgroup example Example: short description of your module
*
* Longer description of your module, including all other files and modules.
*/
/**
* @file
*
* Description of your module's main file.
*
* @ingroup example
*/in the other modules and code files of your module:
/**
* @file
*
* Description of another file in your module.
*
* @ingroup example
*/This way, you get all your modules files related together in the group "example".
Limitations and hints
Drupal's Doxygen processing module, api.module, currently only supports a small subset of all Doxygen commands and makes some assumptions about the formatting of the source. Code to be processed by api.module is advised to stick to these conventions.
Api.module currently supports only one of Doxygen's three grouping mechanisms: Modules (@defgroup, @ingroup, @addtogroup, @{, @}). When using those, please note the following:
- Modules "work at a global level, creating a new page for each group". They should be used only to group functions that provide some kind of API, which possibly spans multiple files. Or the other way round: they should not be used to group functions in a file when these functions are only used in that very file. Thats what Member Groups are for (which unfortunately aren't supported by api.module yet).
@defgroupscan be defined only once - trying to define a second@defgroup namewith a name already used will result in an error. Use@defgroup namein the "most important" section/file of that group and add to it from other places with@addtogroup/@ingroup.- The name in @defgroup name Explaination of that group must be single-word identifier, like a PHP variable or function name. Or, as regular expression:
[a-zA-Z_][a-zA-Z0-9_]*. Dots, hyphens, etc. are not allowed.
To see how a real Doxygen processes and displays the current Drupal code documentation (both core and contrib), have a look at ax' Drupal site. Especially, look at the "doxygen error logs" and help improving Drupals code documentation.
- Login to post comments


