🤯 50% Off! 700+ courses, assessments, and books

Introduction to PhpDoc

    Moshe Teutsch
    Share

    If you’ve ever tried to read code written by someone other than yourself (who hasn’t?), you know it can be a daunting task. A jumble of “spaghetti code” mixed with numerous oddly named variables makes your head spin. Does this function expect a string or an array? Does this variable store an integer or an object? After countless hours of following the threads of code and trying to understand what each bit does, it’s not uncommon to give up and just rewrite the whole thing from scratch – a task that wastes far too much of your precious time.

    PhpDoc, short for PhpDocumentor, is a powerful tool that allows you to easily document your code via specially formatted comments. The documentation will be available not only in the source code, but also in professional documentation extracted using either the web or command-line interface. The result can be in various formats such as HTML, PDF, and CHM. Additionally, many IDEs that provide code-completion can parse PhpDoc comments and provide useful features such as type-hinting. By using PhpDoc, you can make it easy for others (and yourself) to understand your code – weeks, months, and even years after you’ve written it.

    The easiest way to install PhpDoc is with PEAR. Of course, before you can do so you must have PEAR installed. If you don’t, follow the instructions at pear.php.net/manual/en/installation.php.

    In this article I’ll show you how to use PhpDoc to generate gorgeous and user-friendly documentation from beginning to end.

    DocBlocks

    A DocBlock is a multi-line C-style comment used to document a block of code. It begins with /** and has an asterisk at the start of each line. Here’s an example:

    <?php
    /**
     * Calculates sum of squares of an array
     *
     * Loops over each element in the array, squares it, and adds it to 
     * total. Returns total.
     * 
     * This function can also be implemented using array_reduce();
     * 
     * @param array $arr
     * @return int
     * @throws Exception If element in array is not an integer
     */
    function sumOfSquares($arr) {
        $total = 0;
        foreach ($arr as $val) {
            if (!is_int($val)) {
                throw new Exception("Element is not an integer!");
            }
            $total += $val * $val;
        }
        return $total;
    }

    DocBlocks consist of three sections: short description, long description, and tags. All three sections are optional.

    The short description is a succinct description terminated by either a new-line or a period. PhpDoc’s parsing routines are smart; it will only end the short description if the period is at the end of a sentence.

    The long description is where the bulk of the documentation goes; it can be multi-line and as long you wish.

    Both the long and short descriptions may contain certain HTML elements for formatting. HTML tags that aren’t supported will be displayed as plain text. PhpDoc can generate the documentation in multiple formats, though, so the HTML tags aren’t necessarily rendered as they would in an HTML file; the actual formatting depends on the generated file format. If you need to display an HTML tag as text, use double brackets. For example:

    <?php
    /**
     * Here an example of the italics tag: <<i>>Hello, world!<<i>>
     */

    The tags section of a DocBlock contains any number of special tags denoted by the @ symbol. The tags are used to specify additional information, such as the expected parameters and their type. Most tags must be on their own line, with the exception of certain tags which may be inline. Inline tags are surrounded with curly braces and may be in both the long and short description. For a full list of tags, check out the relevant PhpDoc documentation.

    If you need to start a line with the @ symbol but you don’t want it to be interpreted as a tag, you can escape it with a backslash.

    PhpDoc will automatically recognize textual lists in the long and short descriptions and it will parse them. However, it won’t parse nested lists correctly. If you want to use nested lists, use the HTML tags. Here is an example to illustrate what I mean:

    <?php
    /**
     * Example of using lists
     * 
     * PhpDoc will parse this list correctly: 
     * - Item #1
     * - Item #2
     * - Item #3
     * 
     * But not this list:
     * - Item 1
     *   - Item 1.1
     *   - Item 1.2
     * - Item 2
     * 
     * Use this instead for a nested list:
     * <ul>
     *   <li>Item 1</li>
     *   <ul>
     *     <li>Item 1.1</li>
     *     <li>Item 1.2</li>
     *   </ul>
     *   <li>Item 2</li>
     * </ul>
     */

    Packages

    PhpDoc packages are used to group related code elements in the generated documentation. You can specify packages for files and classes and the documented code they contain will inherit the package from them. To specify a package, set the @package tag in a file-level or class-level DocBlock (file-level and class-level DocBlocks will be discussed further is the following section). A package name may contain letters, numbers, dashes, underscores, and square brackets (“[” and “]”).

    Here is an example of defining a file’s package:

    <?php
    /**
     * This is a file-level DocBlock
     * 
     * @package Some_Package
     */

    If you have multiple levels of packages and sub-packages, you can define a sub-package with the @subpackage tag. Here is an example:

    <?php
    /**
     * This is a class-level DocBlock
     * 
     * @package    Some_Package
     * @subpackage Other
     */
    class SomeClass {
    }

    If a file or class doesn’t specify a package it will be set to the default package, “default”. You can specify a different package to be used by default when generating the documentation via the -dn command-line option.

    What Can I Document?

    Not all code elements can be documented with DocBlocks. Here is a list of code elements that may be documented:

    • Files
    • Classes
    • Functions and methods
    • Class properties
    • Global variables
    • include()/require()
    • define()

    All of these elements can use certain common tags, but each has tags that are specific to that element. I’ll go over a few of the elements and the tags normally used to document them.

    Files

    File-level DocBlocks are used to document the contents of a file. It is highly recommended to include a file-level DocBlock in every file you document, and in fact PhpDoc will display a warning if one is not found when generating documentation.

    Most elements are documented by placing a DocBlock before the element, but files are an exception (since you can’t write anything before a file). File-level DocBlocks are placed on the first line of the file.

    A file-level DocBlock usually contains the tags @package, @subpackage, @license, and @author. The @package and @subpackage tags were discussed earlier. The @license tag is used to specify a URL to an external license that covers your code. The tag must contain the URL to the license and optionally a title. The @author tag is used to specify the author of the file. It must contain the author’s name and optionally an email address in angle brackets.

    Unlike most elements, a file-level DocBlock must contain a @package tag in order to be parsed properly.

    Here is a complete example of a file-level DocBlock:

    <?php
    /**
     * This file contains common functions used throughout the application.
     *
     * @package    MyProject
     * @subpackage Common
     * @license    http://opensource.org/licenses/gpl-license.php  GNU Public License
     * @author     Moshe Teutsch <moteutsch@gmail.com>
     */

    Classes

    A class-level DocBlock is placed before a class definition and should describe the meaning of the class. Like file-level DocBlocks, class-level DocBlocks usually contain the tags @package, @subpackage, and @author. Here is an example:

    <?php
    /**
     * An example class
     *
     * The class is empty for the sake of this example.
     *
     * @package    MyProject
     * @subpackage Common
     * @author     Moshe Teutsch <moteutsch@gmail.com>
     */
    class Example {
    }

    Functions and methods

    Functions and methods are documented identically in PhpDoc. (For those who may not be familiar with the terminology, a method is just a function within a class.) Functions and methods usually contain the @param and @return tags in their DocBlocks. The @param tag is used to document the expected type of a parameter. It contains three sections: the parameter, the data type, and an optional description. The @return tag is used to document the return type. It contains two sections: the data type and an optional description. In both tags, the data type can be either a valid PHP data type, a class name, or “mixed”. It can also contain multiple options separated by a pipe.

    <?php
    /**
     * Finds and returns user by ID or username
     *
     * @param int|string $user Either an ID or a username
     * @param PDO $pdo A valid PDO object
     * @return User Returns User object or null if not found
     */
    function getUser($user, PDO $pdo)
    {
        // ...
        if ($isFound) {
            return new User(...);
        }
        return null;
    }

    Generating Documentation

    Once you’ve documented your PHP code, you’ll want to generate user-friendly documentation from it. To do so, run the PhpDoc command-line tool.

    moteutsch@vivaldi:~$ phpdoc -d /path/to/files/ -t /path/to/docs/ -ti 'Documentation Title' -dn 'Default Package' -o HTML:frames:default

    The -d option specifies a comma-separated list of directories containing files to document, and -t the path to generated docs. -ti is used to specify the project title, and -dn to set the default package name. Finally, -o specifies the documentation format. PhpDoc has a wide selection of formats to choose from. A full list is available on the PhpDoc website.

    You can find out more about the command-line tool by executing the help command as follows:

    moteutsch@vivaldi:~$ phpdoc -h

    Once you run the command, the documentation path you specified should contain the generated docs.

    For those of you who aren’t comfortable using the command-line interface, PhpDoc also has a web interface available. It’s outside of this articles scope to discuss it at length, but you can read more about it on PhpDoc’s official website, phpdoc.org.

    Summary

    In this article I’ve given you a first look at PhpDoc and its many powerful features. I have explained the purpose of DocBlocks and their components; I have shown you how to organize your documentation using packages; I have explained which code elements can be documented and some common examples of doing so; finally, I have shown you how to generate documentation from your source code. I highly recommend that you start using PhpDoc in your own projects, if even only to document the most important parts. It is very straight-forward and will save you and your co-workers countless hours of nail-biting and hair-pulling.

    Image via Zadorozhnyi Viktor / Shutterstock