PHP 结合 apidoc生成文档树

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

RenBingo

一点一滴源于你的鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值