Laravel使用命令根据注释一键生成接口名称文档

1、接口注释模板

/**
     * @api {POST} /admin/addAdmin 添加管理员
     * @apiVersion 1.0.0
     * @apiGrouP 管理员
     * @apiParam {String} phone 必填-手机号
     * @apiParam {String} nickname 必填-昵称
     * @apiParam {String} password 必填-密码
     * @apiParam {File} image 选填-头像
     * @apiSuccessExample {json} Success-Response:
     * HTTP/1.1 200 OK
     *
     * @apiSampleRequest off
     * @apiDescription
     * 【author】:浪里小白龙
     * 【createTime】:9:59 2023-07-10
     */
    public function addAdmin(AdminRule $request, AdminService $service)
    {
        $data['phone'] = $request->input('phone');
        $data['nickname'] = $request->input('nickname');
        $data['password'] = $request->input('password');
        $data['image'] = $request->file('image')??'';

        return $this->back($service->addAdmin($data));
    }

2、在namespace App\Console\Commands下创建OperationType类:

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Str;
use ReflectionClass;
use Route;
use DB;
use App\Model\OperationType;
use App\Http\Middleware\VerifyPermissions;
use Artisan;

class OperationTypeSeeder extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'operationType:sync';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '根据注释内容同步操作类型';

    /**
     * 不经过权限验证的路由
     *
     * @var array
     */
    public $exception = [
        'sanctum/csrf-cookie',
    ];

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $sortData = [];

        // 清理表
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        OperationType::query()->truncate();
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');

        foreach (Route::getRoutes()->getRoutes() as $route)
        {
            $action = $route->getAction();

            // 过滤排除路径in_array('get', $route->methods) ||
            if (in_array($route->uri(), $this->exception)) {
                continue;
            }

            // 验证控制器并执行同步
            if (array_key_exists('controller', $action))
            {
                // 获取注释
                $reflector = new ReflectionClass($route->getController());
                $comment = $reflector->getMethod($route->getActionMethod())->getDocComment();

                // 组合kv
                if (preg_match_all('/@(\w+)\s+(.*)\r?\n/m', $comment, $matches)){
                    $result = array_combine($matches[1], $matches[2]);
                }

                // 整理导入数据
                if ($result && isset($result['api'])) {
                    $row = explode(" ",$result['api']);
                    if (empty($row[2])) $row[2]='';
                    $name =  trim($row[2]);
                    $path = trim($row[1]);
                    $path = substr_replace($path, '',0,1);
                    $method = strtolower($route->methods[0]);
                    $module_str = substr($path, 0, 2);
                    if ($module_str == 'wx') {
                        $module = 2;//小程序
                    } else {
                        $module = 1;
                    }
                    $this->createOperationType($name, $path, $method, $module);
                }
            }
        }
    }

    /**
     * 创建权限
     *
     * @param [type] $name 方法名称
     * @param [type] $path 控制器名称和方法名称
     * @param [type] $method 请求方式
     * @param $module int 所属模块:1后台 2小程序
     * @return \App\Model\OperationType
     */
    private function createOperationType($name, $path, $method, $module)
    {
        return OperationType::create([
            'name' => $name,
            'path' => $path,
            'method' => $method,
            'module' => $module,
        ]);
    }
}

3、创建对应的model:App\Model\OperationType

<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;

class OperationType extends Model
{
    //日志类型
    protected $table = 'zs_operation_type';//绑定表
    protected $primaryKey = 't_id';//绑定主键id
    public $timestamps = false;
    protected $fillable = [ //需指定字段,否则无法批量写入
        'name',
        'path',
        'method',
        'module'
    ];
}

Model文件:

class OperationType extends Model
{
    // 操作类型
    protected $table = 'hzy_operation_log';//绑定表
    protected $primaryKey = 'id';//绑定主键id
    public $timestamps = true;
    protected $fillable = [
        'name',
        'path',
        'method',
        'module',
    ];
}

4、指令命令将:数据自动写入数据库

php artisan operation:sync

//该命令获取到的参数
Array
(
    [api] => {POST} /admin/addAdmin 添加管理员
    [apiVersion] => 1.0.0
    [apiGrouP] => 管理员
    [apiParam] => {File} image 选填-头像
    [apiSuccessExample] => {json} Success-Response:
    [apiSampleRequest] => off
    [apiDescription] => * 【author】:浪里小白龙
)

数据库生成的结果:


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Laravel框架一:原理机制篇 Laravel作为在国内国外都颇为流行的PHP框架,风格优雅,其拥有自己的一些特...
    Mr_Z_Heng阅读 3,914评论 0 13
  • Artisan 是 Laravel 的命令行接口的名称,它提供了许多实用的命令来帮助你开发 Laravel 应用,...
    李景磊阅读 609评论 0 0
  • Controller 控制器// 创建一个控制器php artisan make:controller XXXCo...
    VitaAin阅读 1,380评论 0 3
  • Laravel 学习交流 QQ 群:375462817 本文档前言Laravel 文档写的很好,只是新手看起来会有...
    Leonzai阅读 8,649评论 2 12
  • 默认将 Eloquent 的模型直接放置到 app 目录下,开发者可以自行选择放置的位置。对于国内开发者,尤其是 ...
    wz998阅读 1,299评论 0 0

友情链接更多精彩内容