PHP code example of yangweijie / think-scramble

1. Go to this page and download the library: Download yangweijie/think-scramble library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

yangweijie / think-scramble example snippets


return [
    \Yangweijie\ThinkScramble\Service\ScrambleServiceProvider::class,
];


// app/controller/Api.php

namespace app\controller;

use think\Response;

class Api
{
    /**
     * 获取用户列表
     */
    public function users(): Response
    {
        $users = [
            ['id' => 1, 'name' => 'John Doe', 'email' => '[email protected]'],
            ['id' => 2, 'name' => 'Jane Smith', 'email' => '[email protected]'],
        ];

        return json([
            'code' => 200,
            'message' => 'success',
            'data' => $users
        ]);
    }
}


// route/app.php

use think\facade\Route;

Route::group('api', function () {
    Route::get('users', 'Api/users');
    Route::get('users/<id>', 'Api/user');
    Route::post('users', 'Api/createUser');
});



return [
    // API 路径前缀
    'api_path' => 'api',

    // 文档信息
    'info' => [
        'version' => '1.0.0',
        'title' => 'API Documentation',
        'description' => '自动生成的 API 文档',
    ],

    // 输出配置
    'output' => [
        'default_path' => 'public/docs',
        'auto_create_directory' => true,
    ],

    // 缓存配置
    'cache' => [
        'enabled' => true,
        'ttl' => 3600,
    ],

    // UI 配置
    'ui' => [
        'default_renderer' => 'auto', // auto, stoplight-elements, swagger-ui
        'layout' => 'sidebar',        // sidebar, stacked (仅 Stoplight Elements)
    ],

    // 导出配置
    'export' => [
        'default_format' => 'json',
        '

public function createUser(Request $request): Response
{
    // 自动检测 POST 参数
    $name = $request->post('name');     // string
    $age = $request->post('age/d');     // integer
    $email = $request->post('email');   // string

    // 自动分析响应结构
    return json([
        'id' => 123,                    // integer
        'name' => $name,                // string
        'age' => $age,                  // integer
        'email' => $email,              // string
        'created_at' => date('c'),      // datetime
    ]);
}

/**
 * 上传用户头像
 *
 * @upload avatar unction uploadAvatar(Request $request): Response
{
    $avatar = $request->file('avatar');  // 自动识别为文件上传参数
    $userId = $request->param('user_id');

    return json([
        'avatar_url' => '/uploads/avatar.jpg',
        'user_id' => $userId
    ]);
}

/**
 * 批量文件上传
 *
 * @file documents pdf,doc,docx max:50MB 文档文件
 * @param {file} images 图片文件
 */
public function batchUpload(Request $request): Response
{
    // 这些调用会被自动识别为文件上传参数
    $documents = $request->file('documents');
    $images = $request->file('images');

    return json(['success' => true]);
}

/**
 * 用户管理控制器
 *
 * @Route("/api/v1/users")
 * @Middleware("auth")
 */
class UserController
{
    /**
     * 获取用户列表
     *
     * @Get("")
     * @Middleware("throttle:60,1")
     * @Validate("UserValidate", scene="list")
     *
     * @Api {get} /api/v1/users 获取用户列表
     * @ApiParam {Number} page 页码
     * @ApiParam {String} keyword 搜索关键词
     * @ApiSuccess {Array} data.list 用户列表
     */
    public function index(Request $request): Response
    {
        // 自动应用中间件、验证规则,生成 OpenAPI 文档
        return json(['data' => ['list' => []]]);
    }

    /**
     * 创建用户
     *
     * @Post("")
     * @Validate("UserValidate", scene="create")
     *
     * @upload avatar jpg,png max:2MB 用户头像
     * @ApiParam {String} name 用户名
     * @ApiParam {String} email 邮箱
     */
    public function create(Request $request): Response
    {
        // 验证规则自动提取,文件上传自动识别
        return json(['message' => 'created'], 201);
    }
}

/**
 * 用户模型
 *
 * @property int $id 用户ID
 * @property string $username 用户名
 * @property string $email 邮箱地址
 */
class UserModel extends Model
{
    protected $type = [
        'id' => 'integer',
        'username' => 'string',
        'email' => 'string',
        'age' => 'integer',
    ];

    protected $rule = [
        'username' => 'nt $id): Response
{
    // 自动生成包含关联关系的完整 Schema
    return json(UserModel::with('articles')->find($id));
}

/**
 * 安全控制器
 *
 * @middleware auth
 * @middleware throttle:60,1
 */
class SecureController
{
    /**
     * 获取用户信息
     * @Route("users/profile", method="GET")
     * @return Response
     */
    public function profile(): Response
    {
        // 自动生成安全要求:Bearer Token
        return json(['user' => 'data']);
    }

    /**
     * 管理员接口
     * @Route("admin/users", method="GET")
     * @middleware admin
     * @middleware audit:admin_access
     * @return Response
     */
    public function adminUsers(): Response
    {
        // 自动生成安全要求:Bearer Token + 管理员权限
        return json(['admin' => 'data']);
    }

    /**
     * API Key 保护的接口
     * @Route("api/data", method="GET")
     * @middleware api_key
     * @return Response
     */
    public function apiData(): Response
    {
        // 自动生成安全要求:API Key
        return json(['data' => 'protected']);
    }
}

public function store(Request $request): Response
{
    // ThinkScramble 会分析验证规则并生成参数文档
    $validate = \think\facade\Validate::make([
        'name' => 'lidate->getError()], 422);
    }

    // 处理逻辑...
}
bash
php think scramble:generate
bash
php think run
bash
# 基本生成
php think scramble:generate

# 生成到指定位置
php think scramble:generate --output=public/api-docs.json

# 生成 YAML 格式
php think scramble:generate --format=yaml --pretty

# 强制覆盖现有文件
php think scramble:generate --force
bash
# OpenAPI 标准格式
php think scramble:export -f json
php think scramble:export -f yaml
php think scramble:export -f html