¥
立即购买

PHP代码注释生成专家

3 浏览
1 试用
0 购买
Dec 8, 2025更新

本提示词专为PHP开发者设计,能够根据输入的PHP代码片段自动生成专业、准确的技术注释。通过分析代码结构、功能逻辑和业务场景,提供符合编程规范的注释文档,包括函数说明、参数描述、返回值解释等,帮助开发者提高代码可读性和维护性,同时确保注释内容的技术准确性和实用性。

<?php
declare(strict_types=1);

namespace App\Util;

/**
 * 字符串工具类:提供 URL 友好的 slug 生成方法。
 */
final class StrHelper
{
    /**
     * 生成 URL 友好的 slug。
     *
     * 处理流程:
     * - 修剪并归一化空白
     * - 若可用,使用 intl 的 Transliterator 将文本转为 ASCII
     * - 将非字母数字字符替换为分隔符,并修剪首尾分隔符
     * - 可选小写化,并按需限制最大长度
     *
     * 依赖说明:mbstring 必需;intl 可选(提供 Transliterator 时效果更佳)。
     *
     * @param string $title     原始标题,不能为空(会先 trim)
     * @param string $separator 分隔符(用于替换非字母数字字符,且用于首尾修剪),默认 "-"
     * @param bool   $lowercase 是否转换为小写(多字节安全),默认 true
     * @param int    $maxLen    最大长度;<=0 表示不限制,默认 60
     *
     * @return string 生成的 slug 字符串
     *
     * @throws \InvalidArgumentException 当 $title 为空或仅包含空白时
     * @throws \RuntimeException         当处理后无法生成有效的 slug 时
     *
     * @example
     *   use App\Util\StrHelper;
     *   StrHelper::slugify('Hello World!'); // hello-world
     */
    public static function slugify(string $title, string $separator = '-', bool $lowercase = true, int $maxLen = 60): string
    {
        $title = trim($title);
        if ($title === '') {
            throw new \InvalidArgumentException('Title must not be empty.');
        }

        $title = preg_replace('/\s+/u', ' ', $title);

        if (class_exists('Transliterator')) {
            $title = \Transliterator::create('Any-Latin; Latin-ASCII; NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate($title);
        }

        $slug = preg_replace('/[^A-Za-z0-9]+/u', $separator, $title);
        $slug = trim($slug, $separator);

        if ($lowercase) {
            $slug = mb_strtolower($slug, 'UTF-8');
        }

        if ($maxLen > 0) {
            $slug = mb_substr($slug, 0, $maxLen, 'UTF-8');
            $slug = rtrim($slug, $separator);
        }

        if ($slug === '') {
            throw new \RuntimeException('Unable to create slug from given title.');
        }

        return $slug;
    }
}
<?php
declare(strict_types=1);

namespace App\Report;

use DateTimeImmutable;
use RuntimeException;

/**
 * 订单汇总器
 *
 * 将原始订单行数据进行聚合,计算以下指标:
 * - 总订单数(count)
 * - 金额总和(totalAmount)
 * - 平均订单金额(averageAmount,保留两位小数)
 * - 按状态统计数量(byStatus)
 * - 按月份统计金额汇总(byMonth,键格式为 "Y-m")
 *
 * 可选地根据给定状态进行严格等值过滤(仅统计匹配该状态的订单)。
 * 输入数据每行必须包含 id、status、amount、created_at 四个字段,其中 created_at 必须为 "Y-m-d H:i:s" 格式。
 * 汇总结果中的货币固定为 CNY。
 */
final class OrderAggregator
{
    /**
     * 对订单行数据进行聚合汇总。
     *
     * 当提供 $statusFilter 时,仅汇总状态与其完全匹配的订单;未匹配的行将被跳过。
     * 如发现缺失必需字段或 created_at 日期格式无效,将抛出 RuntimeException。
     *
     * @param array<int, array{id:int|string, status:string, amount:float|int|string, created_at:string}> $rows
     *   待汇总的订单行数组:
     *   - id:订单标识(未参与计算,仅用于数据完整性校验)
     *   - status:订单状态(将用于状态过滤及状态统计)
     *   - amount:订单金额(将被强制转换为 float 后参与计算)
     *   - created_at:创建时间,必须为 "Y-m-d H:i:s" 格式,用于按月聚合
     * @param string|null $statusFilter 可选的状态过滤条件(严格等值匹配)
     *
     * @return array{
     *   count:int,
     *   totalAmount:float,
     *   byStatus:array<string,int>,
     *   byMonth:array<string,float>,
     *   currency:string,
     *   averageAmount:float
     * }
     *   汇总结果:
     *   - count:订单数量
     *   - totalAmount:金额合计
     *   - byStatus:按状态的数量统计
     *   - byMonth:按月份("Y-m")的金额合计
     *   - currency:货币代码(恒为 "CNY")
     *   - averageAmount:平均订单金额(两位小数),若 count 为 0 则为 0.0
     *
     * @throws RuntimeException 当行数据缺少必需字段或 created_at 格式无效时抛出
     *
     * @example
     * $rows = [
     *     ['id' => 1, 'status' => 'paid',    'amount' => '99.50', 'created_at' => '2025-05-01 10:30:00'],
     *     ['id' => 2, 'status' => 'pending', 'amount' => 50,      'created_at' => '2025-05-12 08:15:00'],
     *     ['id' => 3, 'status' => 'paid',    'amount' => 20.0,    'created_at' => '2025-06-03 09:45:00'],
     * ];
     *
     * $aggregator = new \App\Report\OrderAggregator();
     * $summary = $aggregator->aggregate($rows, 'paid');
     * // 返回示例:
     * // [
     * //   'count' => 2,
     * //   'totalAmount' => 119.5,
     * //   'byStatus' => ['paid' => 2],
     * //   'byMonth' => ['2025-05' => 99.5, '2025-06' => 20.0],
     * //   'currency' => 'CNY',
     * //   'averageAmount' => 59.75,
     * // ]
     */
    public function aggregate(array $rows, ?string $statusFilter = null): array
    {
        $summary = [
            'count' => 0,
            'totalAmount' => 0.0,
            'byStatus' => [],
            'byMonth' => [],
            'currency' => 'CNY',
        ];

        foreach ($rows as $i => $row) {
            if (!isset($row['id'], $row['status'], $row['amount'], $row['created_at'])) {
                throw new RuntimeException(sprintf('Row #%d missing required fields.', $i));
            }

            if ($statusFilter !== null && $row['status'] !== $statusFilter) {
                continue;
            }

            $amount = (float) $row['amount'];
            $summary['totalAmount'] += $amount;
            $summary['count']++;

            $status = (string) $row['status'];
            $summary['byStatus'][$status] = ($summary['byStatus'][$status] ?? 0) + 1;

            $dt = DateTimeImmutable::createFromFormat('Y-m-d H:i:s', (string) $row['created_at']);
            if (!$dt) {
                throw new RuntimeException(sprintf('Invalid date format at row #%d.', $i));
            }
            $monthKey = $dt->format('Y-m');
            $summary['byMonth'][$monthKey] = ($summary['byMonth'][$monthKey] ?? 0.0) + $amount;
        }

        $summary['averageAmount'] = $summary['count'] > 0 ? round($summary['totalAmount'] / $summary['count'], 2) : 0.0;

        return $summary;
    }
}
<?php
declare(strict_types=1);

namespace App\Integration;

use GuzzleHttp\ClientInterface;
use Psr\Log\LoggerInterface;
use RuntimeException;

/**
 * 用户资料同步服务
 *
 * 通过外部集成端点发起用户资料同步请求,并在成功时返回远端资料快照。
 * 特性:
 * - 最多重试 3 次:网络/解码等异常或非预期响应均会触发重试;
 * - 使用 Guzzle 的 ClientInterface 发送 JSON 请求,超时默认 3 秒;
 * - 采用 PSR-3 Logger 记录成功、警告与错误日志;
 * - 成功判定条件:HTTP 200 且响应体中 ok === true。
 *
 * 使用约定:
 * - $endpoint 为对方系统的基础地址(可包含路径前缀),可带或不带尾部斜杠,方法内部会自行规范化;
 * - 同步成功仅在满足判定条件时返回,失败会在重试用尽后抛出异常。
 */
final class UserSyncService
{
    /**
     * 构造函数
     *
     * @param ClientInterface $http   Guzzle HTTP 客户端实例,用于发送 JSON 请求
     * @param LoggerInterface $logger PSR-3 日志记录器,用于记录同步过程信息与错误
     * @param string          $endpoint 外部集成服务基础 URL(可带或不带尾部斜杠),例如:https://api.partner.com/v1
     */
    public function __construct(
        private ClientInterface $http,
        private LoggerInterface $logger,
        private string $endpoint
    ) {}

    /**
     * 将指定用户的资料与外部系统进行同步,并返回同步结果与资料快照
     *
     * 工作流程:
     * 1. 以 JSON 形式发送 POST 请求到 {endpoint}/profile/sync,载荷为 { userId };
     * 2. 解析 JSON 响应并校验:HTTP 状态码为 200 且数据字段 ok 为 true 视为成功;
     * 3. 出现异常(网络、超时、JSON 解析等)或非预期响应时,最多重试 3 次(异常时每次间隔约 200ms);
     * 4. 重试用尽仍失败则抛出 RuntimeException。
     *
     * 返回值约定:
     * - synced: 恒为 true(仅在成功时返回);
     * - profile: 远端返回的用户资料(若缺失则为空数组);
     * - fetchedAt: 成功获取数据的时间戳(Unix 时间,秒)。
     *
     * @param int $userId 需要同步的用户 ID
     *
     * @return array{
     *     synced: true,
     *     profile: array<mixed>,
     *     fetchedAt: int
     * }
     *
     * @throws RuntimeException 当超过最大重试次数仍无法成功同步时抛出
     */
    public function sync(int $userId): array
    {
        $payload = ['userId' => $userId];
        $attempts = 0;
        $lastError = null;

        while ($attempts < 3) {
            $attempts++;
            try {
                $resp = $this->http->request('POST', rtrim($this->endpoint, '/') . '/profile/sync', [
                    'json' => $payload,
                    'timeout' => 3.0,
                ]);

                $code = $resp->getStatusCode();
                $body = (string) $resp->getBody();
                $data = json_decode($body, true, 512, JSON_THROW_ON_ERROR);

                if ($code === 200 && ($data['ok'] ?? false) === true) {
                    $this->logger->info('User sync success', ['userId' => $userId]);
                    return [
                        'synced' => true,
                        'profile' => $data['profile'] ?? [],
                        'fetchedAt' => time(),
                    ];
                }

                $lastError = 'Unexpected response: ' . $code;
                $this->logger->warning('User sync unexpected response', ['userId' => $userId, 'code' => $code]);
            } catch (\Throwable $e) {
                $lastError = $e->getMessage();
                $this->logger->error('User sync error', ['userId' => $userId, 'error' => $lastError]);
                usleep(200000);
            }
        }

        throw new RuntimeException('Failed to sync user after retries: ' . $lastError);
    }
}

使用示例

use App\Integration\UserSyncService;
use GuzzleHttp\Client;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;

$http = new Client(); // 或基于具体项目配置化创建
$logger = new Logger('sync');
$logger->pushHandler(new StreamHandler('php://stdout'));

$service = new UserSyncService($http, $logger, 'https://api.partner.com/v1');

try {
    $result = $service->sync(12345);
    // $result = ['synced' => true, 'profile' => [...], 'fetchedAt' => 1700000000]
    // TODO: 使用 $result['profile'] 更新本地用户资料
} catch (\RuntimeException $e) {
    // TODO: 告警或补偿逻辑
    $logger->error('Sync failed', ['exception' => $e]);
}

示例详情

解决的问题

  • 一键为任意 PHP 代码片段生成标准、可读、可审的注释(对齐 PHPDoc 规范),覆盖函数说明、参数/返回值、异常与示例。
  • 根据工作阶段灵活调节注释粒度:开发中速写、提测前补全、合并前严谨审阅,减少重复沟通与返工。
  • 让注释准确对齐代码真实行为,拒绝空话和堆砌,确保团队内统一风格与术语。
  • 提升评审与交接效率:PR 前自动补注释,新同事上手更快,重构与回溯更顺畅。
  • 以“可直接粘贴”的结构化输出,缩短从生成到落地的距离,实实在在节省文档时间与人力成本。

适用用户

企业后端工程师

在迭代中为新旧模块快速补齐规范注释,提交前一键生成函数说明、参数与返回值,代码评审更高效。

开源维护者

为仓库中的关键类与公共方法生成一致风格注释,附示例用法,降低贡献者门槛并减少重复问答。

技术团队负责人

统一团队注释标准,推动成员按规范补档,规范代码库文档化,缩短交接与上线前审阅时间。

特征总结

一键为函数、类与方法生成专业注释,涵盖用途、参数、返回值,提交前即可粘贴到代码
自动理解代码意图与业务含义,避免空洞描述,让团队快速读懂模块职责
按需选择详略级别,从轻量概览到完整文档,满足评审、交付与开源发布等场景
注释风格统一且可定制,贴合团队约定,减少多人协作中的风格冲突
自动补充边界条件与异常说明,提前暴露风险点,降低线上故障概率
生成示例用法与调用说明,帮助新人上手与测试同事快速验证功能效果
支持对重构代码进行注释修复,对旧代码补档,提升历史模块可维护性
输出结构清晰、层级分明的注释块,提升阅读效率,审查与合并更顺畅

如何使用购买的提示词模板

1. 直接在外部 Chat 应用中使用

将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。

2. 发布为 API 接口调用

把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。

3. 在 MCP Client 中配置使用

在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。

AI 提示词价格
¥20.00元
先用后买,用好了再付款,超安全!

您购买后可以获得什么

获得完整提示词模板
- 共 492 tokens
- 3 个可调节参数
{ PHP代码 } { 注释详细程度 } { 代码功能类型 }
获得社区贡献内容的使用权
- 精选社区优质案例,助您快速上手提示词
使用提示词兑换券,低至 ¥ 9.9
了解兑换券 →
限时半价

不要错过!

半价获取高级提示词-优惠即将到期

17
:
23
小时
:
59
分钟
:
59