1. Code
  2. PHP
  3. Yii

Programming With Yii: Generating Documentation

Scroll to top
This post is part of a series called How to Program With Yii2.
Programming With Yii2: Building Community With Voting, Comments, and Sharing
This post is part of a series called Building Your Startup With PHP.
How to Build a User Tour With Shepherd in JavaScript
Final product imageFinal product imageFinal product image
What You'll Be Creating

In this Programming With Yii2 series, I'm guiding readers in use of the Yii2 Framework for PHP. You may also be interested in my Introduction to the Yii Framework, which reviews the benefits of Yii and includes an overview of what's new in Yii 2.x.

Welcome! Recently, I wrote about building REST APIs for your Yii application and expanded custom APIs for our startup series application, Meeting Planner.

In today's tutorial, I'll introduce you to Yii's apidoc extension, which automatically generates browsable documentation for your code. I'm going to use it to generate API documentation for Meeting Planner.

Getting Started

Programming With Yii - APIdoc installation GuideProgramming With Yii - APIdoc installation GuideProgramming With Yii - APIdoc installation Guide

Installing apidoc is easy. As shown above, you just add the package using composer.

In addition to generating documentation from code, it's also capable of generating documentation from markdown and transforming this into PDFs.

For example, there is Yii Framework documentation, typical code documentation:

Programming With Yii - Auto-Generated Framework DocumentationProgramming With Yii - Auto-Generated Framework DocumentationProgramming With Yii - Auto-Generated Framework Documentation

And, here is the Yii2 Guide, which I believe is generated from markdown here and integrated with the code documentation for easy browsing:

Programming With Yii Generating Documentation - Guide generated from MarkdownProgramming With Yii Generating Documentation - Guide generated from MarkdownProgramming With Yii Generating Documentation - Guide generated from Markdown

Here's the documentation syntax that apidoc supports; it's based on phpdoc.

Ironically, the documentation for apidoc isn't yet complete, but it's fairly easy to use for basic auto-documentation.

Generating API Documentation

If you've followed along with my startup series, you're aware I'm building an extensive API to support mobile apps, etc. Apidoc is the ideal way for me to maintain dynamic automated documentation for it.

Certainly there are lots of other web services that help you document your API, but I found that Yii's apidoc worked well for my needs, and I appreciated the phpdoc-style theme they use.

Using a standard commenting style makes it likely that other services will be able to easily build documentation from Meeting Planner code if I ever wish to use them.

Creating Comment Blocks

Basically, you create comments within your code that apidoc uses to build your documentation. It's described within the Yii coding style guide.

You place a comment block at the top of each file like this one:

1
<?php
2
/**

3
 * @link https://meetingplanner.io

4
 * @copyright Copyright (c) 2016 Lookahead Consulting

5
 * @license https://github.com/newscloud/mp/blob/master/LICENSE

6
 */

And you place a comment block above each controller or model definition:

1
/**

2
 * UserTokenController provides API functionality for registration, delete and verify

3
 *

4
 * @author Jeff Reifman <jeff@meetingplanner.io>

5
 * @since 0.1

6
 */
7
class UserTokenController extends Controller
8
{

Then, you place a detailed comment block above each method, which includes parameters, return values, and exceptions:

1
/**

2
     * Register a new user with an external social Oauth_token

3
     *

4
     * @param string $signature the hash generated with app_secret

5
     * @param string $app_id in header, the shared secret application id

6
     * @param string $email in header, email address

7
     * @param string $firstname in header, first name

8
     * @param string $lastname in header, last name

9
     * @param string $oauth_token in header, the token returned from Facebook during OAuth for this user

10
     * @param string $source in header, the source that the $oauth_token is from e.g. 'facebook' e.g. [$oauth_token]

11
     * @return obj $identityObj with user_id and user_token

12
     * @throws Exception not yet implemented

13
     */
14
    public function actionRegister($signature,$app_id='',$email='',$firstname ='',$lastname='',$oauth_token='',$source='') {

You must follow the prescribed layout as described to feed apidoc successfully. 

Using Placeholder Arguments for API Documentation

The Yii team developed apidoc to generate code documentation. However, as I wrote about in Securing Your API, all but the hash signature argument has been moved to http headers. These are invisible to apidoc. Thus, to generate API documentation, I decided to use a workaround.

As you can see, I include dummy arguments in the methods and then specify in the comments that these are sent as headers or "in header."

1
* @param string $signature the hash generated with app_secret
2
* @param string $app_id in header, the shared secret application id
3
* @param string $email in header, email address
4
* @param string $firstname in header, first name
5
* @param string $lastname in header, last name

As long as default values are included in the function definitions, there's no real harm done:

1
public function actionRegister($signature,$app_id='',$email='',$firstname ='',
2
    $lastname='',$oauth_token='',$source='') {

In a moment, you'll see how this generally works for API documentation, even if it's not optimal coding style.

Let's move on to actually using apidoc to generate the documentation.

Generating the Documentation

You can review apidoc commands by running it without arguments:

1
$ ./vendor/bin/apidoc
2
3
This is Yii version 2.0.10.
4
5
The following commands are available:
6
7
- api                      Generate class API documentation.
8
    api/index (default)    Renders API documentation files
9
10
- guide                    This command can render documentation stored as
11
                           markdown files such as the yii guide
12
    guide/index (default)  Renders API documentation files
13
14
- help                     Provides help information about console commands.
15
    help/index (default)   Displays available commands or the detailed
16
                           information
17
18
19
To see the help of each command, enter:
20
21
  apidoc help <command-name>

I'll use the api option, and here are the configurations you can make:

1
$ ./vendor/bin/apidoc help api
2
3
DESCRIPTION
4
5
Renders API documentation files
6
7
8
USAGE
9
10
apidoc api <sourceDirs> <targetDir> [...options...]
11
12
- sourceDirs (required): array
13
  $sourceDirs
14
15
- targetDir (required): string
16
  $targetDir
17
18
19
OPTIONS
20
21
--appconfig: string
22
  custom application configuration file path.
23
  If not set, default application configuration is used.
24
25
--color: boolean, 0 or 1
26
  whether to enable ANSI color in the output.
27
  If not set, ANSI color will only be enabled for terminals that support it.
28
29
--exclude: string|array
30
  files to exclude.
31
32
--guide: string
33
  url to where the guide files are located
34
35
--guidePrefix: string (defaults to 'guide-')
36
  prefix to prepend to all guide file names.
37
38
--help, -h: boolean, 0 or 1
39
  whether to display help information about current command.
40
41
--interactive: boolean, 0 or 1 (defaults to 1)
42
  whether to run the command interactively.
43
44
--pageTitle: string
45
  page title
46
47
--template: string (defaults to 'bootstrap')
48
  template to use for rendering

To generate my API documentation, whose directory is also api, I'll do the following:

1
$ ./vendor/bin/apidoc api api api/web/docs 
2
    --pageTitle=MeetingPlanner
3
TargetDirectory already exists. Overwrite? (yes|no) [yes]:yes
4
Searching files to process... done.
5
Loading apidoc data from cache... done.
6
Checking for updated files... done.
7
8 files to update.
8
Processing files... done.
9
Updating cross references and backlinks... done.
10
Rendering files: done.
11
generating extension index files...done.
12
generating search index...done.
13
35 errors have been logged to api/web/docs/errors.txt
14
214 warnings have been logged to api/web/docs/warnings.txt

Because I haven't finished commenting the entire tree, there are errors and warnings generated. They most often look something like this:

1
Array
2
(
3
    [0] => Array
4
        (
5
            [line] => 31
6
            [file] => api/controllers/ParticipantController.php
7
            [message] => Method behaviors has no parent to inherit from in api\controllers\ParticipantController.
8
        )
9
10
    [1] => Array
11
        (
12
            [line] => 32
13
            [file] => api/controllers/PlaceController.php
14
            [message] => Method behaviors has no parent to inherit from in api\controllers\PlaceController.
15
        )

Browsing the Documentation

Publishing the documentation in the above apidoc command line to /api/web/docs means that you can browse the Meeting Planner documentation from the web.

For example, here's the UserTokenController:

Programming With Yii Generating Documentation - UserTokenController ExampleProgramming With Yii Generating Documentation - UserTokenController ExampleProgramming With Yii Generating Documentation - UserTokenController Example

Here is the actionRegister() method showing the parameter comments reflected with the in header information.

Programming With Yii Generating Documentation - UserTokenController Example actionRegister methodProgramming With Yii Generating Documentation - UserTokenController Example actionRegister methodProgramming With Yii Generating Documentation - UserTokenController Example actionRegister method

Here's the MeetingController documentation:

Programming With Yii Generating Documentation - MeetingController ExampleProgramming With Yii Generating Documentation - MeetingController ExampleProgramming With Yii Generating Documentation - MeetingController Example

And, here is the actionMeetingplacechoices() method:

Programming With Yii Generating Documentation - MeetingController Example actionMeetingplaces exampleProgramming With Yii Generating Documentation - MeetingController Example actionMeetingplaces exampleProgramming With Yii Generating Documentation - MeetingController Example actionMeetingplaces example

As you can see, this is extremely useful for sharing an API with third-party programmers in real time as you deliver the code. The great benefit is that it eliminates the need to manually maintain API documentation separately.

Anytime you can eliminate a task for a startup, it's a huge win.

Looking Ahead

I hope that you've seen a bit of the power of Yii2's apidoc extension. You can use it to maintain documentation for all your code, and also it encourages you to keep up with comments, which I'll do more of now.

If you have any questions or feedback, please post them in the comments. If you'd like to keep up on my future Envato Tuts+ tutorials and other series, please visit my instructor page or follow @reifman. Definitely check out my startup series and Meeting Planner.

Related Links

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.