PHP 结合 apidoc生成文档树

来源:互联网 发布:网易闪电邮 for mac 编辑:程序博客网 时间:2024/06/07 18:09

apidoc的使用可以参考http://apidocjs.com/

以下是使用PHP生成 apidoc能解析的文档树,方便开发人员尽快的输出文档,以下是方法,
将其放到公共控制器下,每次请求都调用一下,时时监听api.log,会生成一个

/**
* @api {post} login/index1
* @apiName index1
* @apiGroup login
*
* @apiParam {string} mobile
*
* @apiSuccess {int} errcode
* @apiSuccess {string} errmsg
* @apiSuccess {object} data
* @apiSuccess {string} data.mobile
* @apiSuccess {string} data.is_create
*
* @apiSuccessExample Success-Response:
{
“errcode”: 0,
“errmsg”: “操作成功”,
“data”: {
“mobile”: “12345678910”,
“is_create”: “1”
}
}
*/

如下生成的代码:

/** * 创建apidoc文档 * @param $data */public function create_api($data) {    $str = "/**" . PHP_EOL;    $url = uri_string();    $str .= ' * @api {' . strtolower($_SERVER['REQUEST_METHOD']) . '} ' . $url . PHP_EOL;    list($one, $two) = explode('/', $url);    $str .= ' * @apiName ' . $two . PHP_EOL;    $str .= ' * @apiGroup ' . $one . PHP_EOL;    $str .= ' *' . PHP_EOL;    $request = $this->input->post(null);    if (!empty( $request )) {        foreach ($request as $k => $v) {            if ($k == 'is_create') {                continue;            }            $str .= ' * @apiParam {string} ' . $k . PHP_EOL;        }        $str .= ' *' . PHP_EOL;    }    $str .= $this->get_re($data, '', 1);    $str .= ' *' . PHP_EOL;    $str .= ' * @apiSuccessExample Success-Response:' . PHP_EOL;    $str .= json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);    $str = str_replace(['integer', 'array'], ['int', 'object'], $str);    $str .= PHP_EOL . ' */' . PHP_EOL;    $config =& get_config();    file_put_contents($config['log_path'] . '/api.log', PHP_EOL . $str, FILE_APPEND);}public function get_re($data, $pre = '', $deep = 1) {    if ($deep > 10) {        return false;    }    global $str;    foreach ($data as $index => $item) {        $is_num = is_numeric($index);        $is_arr = is_array($item);        if ($is_arr) {            if ($is_num) {                if (strpos($str, $pre)) {                    break;                } else {                    $this->get_re($item, $pre, $deep);                }            } else {                $str .= ' * @apiSuccess {' . gettype($item) . '} ' . $pre . $index . PHP_EOL;                $deep = $deep + 1;                $this->get_re($item, $pre . $index . '.', $deep);            }        } else {            $str .= ' * @apiSuccess {' . gettype($item) . '} ' . $pre . $index . PHP_EOL;        }    }    return $str;}
原创粉丝点击