本文目录导读:

在PHP中生成API文本摘要,通常有几种常见做法,我来给你详细介绍:
使用函数注释生成摘要(推荐)
基础格式
/**
* @OA\Get(
* path="/api/users",
* summary="获取用户列表",
* description="返回所有活跃用户的详细信息列表"
* )
*/
public function getUsers() {
// 处理逻辑
}
完整示例 - 使用swagger-php
<?php
namespace App\Controllers;
use OpenApi\Annotations as OA;
class UserController
{
/**
* @OA\Get(
* path="/api/users/{id}",
* summary="获取指定用户信息",
* description="根据用户ID返回详细的用户信息,包括个人资料和权限",
* tags={"用户管理"},
* @OA\Parameter(
* name="id",
* in="path",
* required=true,
* description="用户ID",
* @OA\Schema(type="integer")
* ),
* @OA\Response(
* response=200,
* description="成功返回用户信息",
* @OA\JsonContent(
* type="object",
* @OA\Property(property="id", type="integer"),
* @OA\Property(property="name", type="string"),
* @OA\Property(property="email", type="string")
* )
* ),
* @OA\Response(
* response=404,
* description="用户不存在"
* )
* )
*/
public function getUser(int $id)
{
// 业务逻辑
return response()->json([
'id' => $id,
'name' => '张三',
'email' => 'zhangsan@example.com'
]);
}
}
手动生成文本摘要
<?php
class ApiDocumentation
{
/**
* 生成API摘要
*/
public function generateSummary($apiData)
{
$summary = [];
// 基本摘要信息
$summary['title'] = $apiData['name'] ?? '';
$summary['description'] = $this->truncateText($apiData['description'] ?? '', 100);
// HTTP方法相关信息
$summary['method'] = strtoupper($apiData['method'] ?? 'GET');
$summary['endpoint'] = $apiData['path'] ?? '';
// 参数摘要
if (!empty($apiData['parameters'])) {
$summary['params'] = count($apiData['parameters']) . ' 个参数';
}
// 权限摘要
if (!empty($apiData['auth'])) {
$summary['auth'] = $apiData['auth'];
}
return $summary;
}
private function truncateText($text, $length)
{
if (mb_strlen($text) > $length) {
return mb_substr($text, 0, $length) . '...';
}
return $text;
}
}
使用第三方包自动生成
安装swagger-php
composer require zircote/swagger-php
使用示例
<?php
use OpenApi\Analyser;
use OpenApi\Analysis;
use OpenApi\Annotations\OpenApi;
// 扫描控制器目录
$openapi = \OpenApi\scan('/path/to/controllers');
// 输出为JSON
$apiDocumentation = $openapi->toJson();
信息
function extractSummaries($apiDoc) {
$summaries = [];
foreach ($apiDoc['paths'] as $path => $methods) {
foreach ($methods as $method => $details) {
$summaries[] = [
'endpoint' => $path,
'method' => strtoupper($method),
'summary' => $details['summary'] ?? '',
'description' => $details['description'] ?? ''
];
}
}
return $summaries;
}
$apiDoc = json_decode($apiDocumentation, true);
$summaries = extractSummaries($apiDoc);
自动化生成摘要的函数
<?php
class ApiSummaryGenerator
{
private $apiEndpoints = [];
/**
* 注册API端点
*/
public function registerEndpoint(string $method, string $path, array $options = [])
{
$this->apiEndpoints[] = [
'method' => $method,
'path' => $path,
'summary' => $options['summary'] ?? '',
'description' => $options['description'] ?? '',
'tags' => $options['tags'] ?? [],
'deprecated' => $options['deprecated'] ?? false,
'version' => $options['version'] ?? '1.0',
'parameters' => $options['parameters'] ?? []
];
}
/**
* 生成文本摘要
*/
public function generateTextSummary(): string
{
$output = "API文档摘要\n";
$output .= str_repeat("=", 50) . "\n\n";
$grouped = $this->groupByTags();
foreach ($grouped as $tag => $endpoints) {
$output .= "【{$tag}】\n";
$output .= str_repeat("-", 30) . "\n";
foreach ($endpoints as $endpoint) {
$deprecated = $endpoint['deprecated'] ? ' [已弃用]' : '';
$output .= sprintf(
" %s %s%s\n",
$endpoint['method'],
$endpoint['path'],
$deprecated
);
$output .= sprintf(" ↳ %s\n", $endpoint['summary']);
$output .= sprintf(" ↳ 版本: %s\n", $endpoint['version']);
$output .= "\n";
}
}
return $output;
}
private function groupByTags(): array
{
$grouped = [];
foreach ($this->apiEndpoints as $endpoint) {
$tags = $endpoint['tags'] ?: ['默认'];
foreach ($tags as $tag) {
$grouped[$tag][] = $endpoint;
}
}
return $grouped;
}
}
// 使用示例
$generator = new ApiSummaryGenerator();
$generator->registerEndpoint('GET', '/api/users', [
'summary' => '获取用户列表',
'description' => '分页获取所有用户信息',
'tags' => ['用户管理'],
'version' => '2.0'
]);
$generator->registerEndpoint('POST', '/api/users', [
'summary' => '创建新用户',
'description' => '创建新的用户账户',
'tags' => ['用户管理'],
'version' => '1.0'
]);
echo $generator->generateTextSummary();
Laravel中的API资源文档生成
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\User;
class UserController extends Controller
{
/**
* @api {get} /api/users 获取用户列表
* @apiName GetUsers
* @apiGroup User
* @apiVersion 0.1.0
*
* @apiSuccess {Integer} id 用户ID
* @apiSuccess {String} name 用户名
* @apiSuccess {String} email 邮箱
*
* @apiSampleRequest /api/users
*/
public function index()
{
return User::paginate(10);
}
}
最佳实践建议
- 使用标准格式:推荐遵循OpenAPI/Swagger规范
- 保持摘要简洁:摘要应控制在50-100字内
- 版本控制:在摘要中包含API版本信息
- 自动化生成:使用CI/CD流水线自动生成文档
- 及时更新:每次修改API后同步更新摘要
选择哪种方式取决于你的项目需求,如果是简单项目,使用注释方式就足够了;如果是大型项目,建议使用swagger-php等成熟方案。