WSDB.NET: web-programming, software development, data bases

 Главная | Команда| Направления | Библиотекакарта сайта |  

Заметки на салфетках » Как автоматизировать документирование кода

Как автоматизировать документирование кода

Один опыт я ставлю выше, чем тысячу мнений, рожденных только воображением.
Михаил Ломоносов 

Разработчик при работе над проектом рано или поздно сталкивается с необходимостью документирования кода. Это бывает вызвано разными причинами. Работа в команде, предоставление описания API сторонним людям.

Для меня же стало актуальным просто разобраться в том, что уже написано и давно работает. Чего уже только не перепробовал. И в тетрадку писал, и в Worde, последней попыткой было создание некоего подобия системы документирования. Все это только замедляло процесс разработки и грозило сорвать сроки по проекту. Количество кода росло, в некоторых случаях приходилось переписывать одно и то же.

И вот в одном из проектов мне довелось столкнуться с классом для отправки почты PHPMailer - PHP email class (Class for sending email using either sendmail, PHP mail(), or SMTP. Methods are based upon the standard AspEmail(tm) classes.) Copyright (C) 2001 - 2003 Brent R. Matzelle. При просмотре кода обратил внимание, что он очень аккуратно написан и легко читается. Затем открыл документацию по этому классу и увидел такую надпись "This documentation was generated by phpDocumentor v1.2.0" со ссылкой на http://www.phpdoc.org/

Ага, думаю, вот ОНО, наконец-то!

Пошел на сайт, скачал себе дистрибутив, установил, немного повозился с настройкой и сделал первый запуск. На выходе естественно ничего не получил, так как тогдашний мой стиль написания кода был далек от требований phpDocumentor'a.

Справка о том как это работает.

В каждом файле проекта, а также перед каждым значимым элементом, таким как функция, константа и т.п. нужно сделать специальный комментарий.

Пример комментария для файла:

/**
* SmartyCMS
* Описание модуля SmartyCMS
* @package SmartyCMS
* @author Aleksandr Datsko
* @version 1.0, 03.07.2007
* @since engine v.1.0
* @copyright (c) 2006+ by Aleksandr Datsko
*/

Первая строка означает имя или предназначение данного файла.
Далее следует краткое описание. Описание может быть многострочным.
@package - принадлежность файла к какому-либо пакету или части проекта
@author - указывается автор
@version - информация о версии
@since - когда данный файл появился или стал доступен для использования в проекте
@copyright - сведения об авторских правах

Пример комментирования функции:

/**
* Название функции
* Описание функции
* @param integer $t комментарий к параметру
* @return string
*/
function myFunctio( $t ){

if( $t == "text" )
{
retun "ok";
}
else
{
return "error";
}

}

Первые две строки аналогичны комментарию файла.
@param описывает параметр функции
@return - ее результат

Пример комментирования константы:

/** t constant */
define( "t", "Simple Text" );

Комментирование классов:

Комментирование классов включает в себя все предыдущие виды комментирования.
Перед описанием класса ставится комментарий аналогичный тому, что делается в начале файла.
Свойство описывается при помощи ключевого слова @var.
Метод описывается по аналогии с описанием фугкции.

 

Справочник ключевых слов, используемых в комментариях и их формат (phpDocumentor tags):

@abstract - Document an abstract class, class variable or method
/**
* example of basic @abstract usage in a class
* Use this if every single element of the class is abstract
* @abstract
*/

@access - Access control for an element. @access private prevents documentation of the following element (if enabled).
@access private protected public
/**
* function func2, access is private, will not be documented
* @access private
*/

@author - Author of current element
@author authorname < ... >
/**
* function datafunction
* another contributor authored this function
* @author Joe Shmoe
*/

@category - Specify a category to organize the documented element's package into
@category categoryname
/**
* Page-Level DocBlock
* @package MyPackage
* @category mycategory
*/

@copyright - Document Copyright information
@copyright copyright information
/**
* Page-Level DocBlock example.
* @author Gregory Beaver < cellog@php.net >
* @copyright Copyright (c) 2002, Gregory Beaver
*/

@deprecated - Document elements that have been deprecated and should not be used as they may be removed at any time from a future version
@deprecated version/info string
/**
* @deprecated deprecated since version 2.0
*/

@example - Include an external example file with syntax highlighting
@example /path/to/example.php description
@example url://path/to/example.php description
@example relativepath/to/example.php description
/**
* My function
*
* Here is an inline example:
* < code >
* < ? php
* echo strlen('6');
* ? >
* < /code >
* @example /path/to/example.php How to use this function
* @example anotherexample.inc This example is in the "examples" subdirectory
*/

@final - Document a class method that should never be overridden in a child class
@final
/**
* function1 should never be overridden
* @final
*/

@filesource - Create a syntax-highlighted cross-referenced file containing source code of the current file and link to it
@filesource
/**
* Contains several example classes that I want to parse but I
* also want to show the full source
* @package mypackage
* @subpackage example
* @filesource
*/

@global - Document a global variable, or its use in a function/method
@global datatype $globalvariablename
@global datatype description
/** example of correct @global declaration,
* even with many irrelevant things in between
* @global mixed $_GLOBALS["myvar"]
* @global bool used to control the weather
*/

@ignore - Prevent documentation of an element
@ignore
/**
* @ignore
*/

@internal - Mark documentation as private, internal to the software project
@internal any information that should not be displayed in public documentation [unspecified format]
/**
* This class does things
*
* {@internal To access the company guidelines on modifying this class,
* see {@link http://www.example.com Company Guidelines}, or contact
* your supervisor}}}
* Using this class can be very helpful for several reasons. etc. etc.
* @internal the class uses the private methods {@link _foo()} and
* {@link _bar()} to do some wacky stuff
*/

@license - Display a hyperlink to a URL for a license
@license URL name of license
/**
* Displays < a xhref="http://opensource.org/licenses/gpl-license.php" mce_href="http://opensource.org/licenses/gpl-license.php" >GNU Public License< /a >
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

@link - Display a hyperlink to a URL in the documentation
@link URL link text
@link URL, URL, URL...
/**
* Displays < a xhref="http://www.example.com" mce_href="http://www.example.com" >http://www.example.com< /a >
* @link http://www.example.com
* @link http://www.example.com Hello
*/

@method - Magic" Method of a class
@method returntype description
/**
* show off @method
*
* @method int borp() borp(int $int1, int $int2) multiply two integers
*/

@name - Specify an alias to use for a procedural page or global variable in displayed documentation and linking
@name $globalvariablename
/**
* Now, when @global is used in a function, it will link to $baz
* @name $baz
* @global array $GLOBALS['baz']
*/

@package - Specify package to group classes or functions and defines into
@package packagename
/**
* Page-Level DocBlock example.
* This DocBlock precedes another DocBlock and will be parsed as the page-level.
* Put your @package and @subpackage tags here
* @package pagelevel_package
*/

@param - Document a function parameter
@param datatype $paramname description
@param datatype1|datatype2 $paramname description
/**
* example of basic @param usage
* @param bool $baz
* @return mixed
*/
/**
* Example of documenting multiple possible datatypes for a given parameter
* @param bool|string $foo sometimes a boolean, sometimes a string (or, could have just used "mixed")
* @param bool|int $bar sometimes a boolean, sometimes an int (again, could have just used "mixed")
*/

@property - Magic" Property of a class
@property datatype description
/**
* show off @property, @property-read, @property-write
*
* @property mixed $regular regular read/write property
* @property-read int $foo the foo prop
* @property-write string $bar the bar prop
*/

@return - Specify the return type of a function or method
@return datatype description
@return datatype1|datatype2 description
/**
* example of basic @return usage
* @return mixed
*/
/**
* example of showing multiple possible return types
* @return int|string could be an int, could be a string
*/

@see - Display a link to the documentation for an element
@see file.ext|elementname|class::methodname()|class::$variablename|functionname()|function functionname unlimited number of values separated by commas
/**
* class 1
*
* @see subclass::method()
* @see subclass
* @see subclass::$foo
* @see main_class, TEST_CONST
*/

@since - Document when (at which version) an element was first added to a package
@since version/info string [unspecified format]
/**
* function datafunction
* @since Version 21.1
*/

@static - Document a static property or method
@static
/**
* a static function
* @static
*/

@staticvar - Document a static variable's use in a function/method
@staticvar datatype description
/**
* example of basic @staticvar usage in a function
* @staticvar integer used to calculate the division tables
* @staticvar array $bar is used to make me happy. Note that $bar is part of the description
*/

@subpackage - Specify sub-package to group classes or functions and defines into. Requires @package tag
@subpackage subpackagename
/**
* Page-Level DocBlock example.
* This DocBlock precedes another DocBlock and will be parsed as the page-level.
* Put your @package and @subpackage tags here
* @package pagelevel_package
* @subpackage data
*/

@todo - Document changes that will be made in the future
@todo information string [unspecified format]
/**
* Page-level DocBlock
* @package unfinished
* @todo finish the functions on this page
*/

@tutorial - Display a link to the documentation for a tutorial
@tutorial package/ subpackage/ tutorialname.ext #section.subsection description
/**
* This will link to the phpDocumentor.pkg tutorial if it is unique, regardless
* of its location
* @tutorial phpDocumentor.pkg
* @tutorial phpDocumentor/phpDocumentor.pkg
* @tutorial phpDocumentor/info/phpDocumentor.pkg
* @tutorial phpDocumentor.pkg#section1, phpDocumentor.pkg#section1.subsection1
*/

@uses - Display a link to the documentation for an element, and create a backlink in the other element's documentation to this
@uses file.ext|elementname|class::methodname()|class::$variablename|functionname()|function functionname description of how the element is used
/**
* subclass inherits this method.
* example of a word which is either a constant or class name,
* in this case a classname
* @uses subclass sets a temporary variable
* @uses subclass::$foo this is compared to TEST_CONST
* @uses TEST_CONST compared to subclass::$foo, we
* die() if not found
*/

@var - Document the data type of a class variable
@var datatype description
/**
* example of documenting a variable's type
* @var string contains class1 information
*/

@version - Version of current element
@version versionstring [unspecified format]
/**
* example of @version tag with CVS tag
* @version $Id: tags.version.pkg,v 1.2 2006/04/29 04:08:27 cellog Exp $;
* @version customversionstring1.0
*/

 

phpDocumentor Inline tags

inline {@example} - Display source code of an example file inline
{@example /path/to/example.php startline number of lines }
{@example url://path/to/example.php startline number of lines }
{@example relative/path/to/example.php startline number of lines }
/**
* My function
*
* Here is an inline example:
* < code >
* < ?php
* echo strlen('6');
* ? >
* < /code >
* and using an external example file:
* {@example /path/to/example.php}
*
* Display only the first 2 lines:
* {@example /path/to/example.php 0 2}
* @example /path/to/example.php How to use this function
* @example anotherexample.inc This example is in the "examples" subdirectory
*/

inline {@id} - Used to control XML tutorial ids in refsects
{@id sectionname }

inline {@internal}} - Mark documentation as private, internal to the software project in text flow
{@internal any text including inline tags }}

inline {@inheritdoc} - Used to directly inherit the long description from the parent class in child classes
{@inheritdoc}
/**
* Makes chocolate bars
*
* There are two aspects to this class.
* {@inheritdoc } In addition, the foo class
* makes the bars chocolate
*/

inline {@link} - Display a link to a URL, or link to an element's documentation in the the flow of descriptive text
{@link URL description }
{@link element description }
/**
* Text with a normal @see and @link tag
* @see element
* @link http://www.example.com
*/

inline {@source} - Display source code of a function or method in the long description
{@source startline number of lines }
/**
* Text with an inline source tag:
*
* {@source }
* displays without a break in the flow
*/

inline {@toc} - Display a table of contents of all {@id}s declared in a file
{@toc}

inline {@tutorial} - Display a link to a tutorial in the the flow of descriptive text
{@tutorial package/ subpackage/ tutorialname.ext #section.subsection description } }
/**
* Text with an inline link to {@tutorial phpDocumentor/phpDocumentor.pkg} displays
* without a break in the flow
*/

Более подробное описание всех ключевых слов phpDocumentor - http://manual.phpdoc.org/HTMLSmartyConverter/HandS/phpDocumentor/tutorial_phpDocumentor.pkg.html

Заметки на салфетках » Как автоматизировать документирование кода

© 2005-2008 wsdb.net