How to use DocBlock Templates in PHPDoc

Sometimes one has several variables that are related – typically in a class – and one wants to document them with PHPDoc. Defining the same type and perhaps description for each of these variables or constants can be tedious and result in a lot of redundant documentation. Luckily, PHPDoc provides a way of documenting multiple variables or constants at once without specifying multiple DocBlocks. This is done with so-called DocBlock templates.

A DocBlock template begins with /**#@+ and ends with /**#@-*/. Between these strings is the usual definitions that we know from PHPDoc, along with the variable declarations. This is demonstrated in the following example.


class Http extends Connection
{
    /**#@+
     * @var int
     */
    const STATUS_OK = 200;
    const STATUS_MOVED_PERMANENTLY = 301;
    const STATUS_FORBIDDEN = 403;
    const STATUS_NOT_FOUND = 404;
    const STATUS_INTERNAL_SERVER_ERROR = 500;
    const STATUS_BAD_GATEWAY = 502;
    /**#@-*/

    // ...
}

In the above example, we define several constants as being integers all at once. Any number of variables or constants can be grouped together and declared to be of a certain type. However, this should only be done when they are also related as in the above example. Note that other PHPDoc declarations can be used (or descriptive texts); this example merely uses @var for simplicity. To demonstrate why DocBlock templates are worth the trouble, here is the same example without DocBlock templates.


class Http extends Connection
{
    /**
     * @var int
     */
    const STATUS_OK = 200;

    /**
     * @var int
     */
    const STATUS_MOVED_PERMANENTLY = 301;

    /**
     * @var int
     */
    const STATUS_FORBIDDEN = 403;

    /**
     * @var int
     */
    const STATUS_NOT_FOUND = 404;

    /**
     * @var int
     */
    const STATUS_INTERNAL_SERVER_ERROR = 500;

    /**
     * @var int
     */
    const STATUS_BAD_GATEWAY = 502;

    // ...
}

As you can see, that takes up quite a bit of space. Surely one could shorten the DocBlocks, but one would still have to type them out. Even with the help of an IDE, this is just not as pretty and does not really indicate in any way that a group of variables or constants are related.

This article is just a quick introduction to DocBlock templates in PHPDoc (and a reference for myself). For further information, please read the DocBlock Templates section at phpdoc.org.

One Comment

  1. Gilberto Ramos said:

    Great! I didn’t know DocBlock even exists.. thanks!

    July 20, 2016
    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *