本文目录导读:

我来为您设计一个PHP项目性能报表自动生成对比分析文档的完整方案。
整体架构设计
graph TB
A[性能数据采集] --> B[数据存储]
B --> C[数据对比分析]
C --> D[文档生成]
D --> E[报告输出]
subgraph 采集层
A1[XHProf/Blackfire]
A2[自定义埋点]
A3[服务器监控]
end
subgraph 分析层
C1[基准对比]
C2[趋势分析]
C3[异常检测]
end
subgraph 输出层
E1[PDF报告]
E2[HTML报告]
E3[邮件推送]
end
核心代码实现
1 性能数据采集器
<?php
// PerformanceCollector.php
class PerformanceCollector {
private $db;
private $metrics = [];
public function __construct() {
$this->db = new PDO('mysql:host=localhost;dbname=performance', 'user', 'password');
}
/**
* 采集性能指标
*/
public function collectMetrics($projectId, $version) {
$metrics = [
'response_time' => $this->getAvgResponseTime(),
'memory_usage' => memory_get_peak_usage(true),
'cpu_usage' => $this->getCpuUsage(),
'db_queries' => $this->getDbQueryCount(),
'cache_hit_rate' => $this->getCacheHitRate(),
'error_rate' => $this->getErrorRate(),
'throughput' => $this->getThroughput(),
'timestamp' => time()
];
$this->saveMetrics($projectId, $version, $metrics);
return $metrics;
}
/**
* 获取API端点性能
*/
public function collectEndpointMetrics() {
$endpoints = [
'/api/users',
'/api/products',
'/api/orders'
];
$endpointMetrics = [];
foreach ($endpoints as $endpoint) {
$start = microtime(true);
// 模拟请求
usleep(rand(10000, 50000));
$duration = microtime(true) - $start;
$endpointMetrics[$endpoint] = [
'avg_response_time' => $duration * 1000, // ms
'p95_response_time' => $duration * 1.5 * 1000,
'p99_response_time' => $duration * 2 * 1000,
'requests_per_minute' => rand(100, 1000)
];
}
return $endpointMetrics;
}
}
2 性能对比分析器
<?php
// PerformanceAnalyzer.php
class PerformanceAnalyzer {
private $collector;
public function __construct() {
$this->collector = new PerformanceCollector();
}
/**
* 生成对比分析报告
*/
public function generateComparisonReport($projectId, $baselineVersion, $currentVersion) {
$baseline = $this->getVersionMetrics($projectId, $baselineVersion);
$current = $this->getVersionMetrics($projectId, $currentVersion);
$comparison = [
'summary' => $this->compareOverallMetrics($baseline, $current),
'endpoints' => $this->compareEndpointMetrics($baseline['endpoints'], $current['endpoints']),
'degradations' => $this->detectDegradations($baseline, $current),
'improvements' => $this->detectImprovements($baseline, $current),
'recommendations' => $this->generateRecommendations($baseline, $current)
];
return $comparison;
}
/**
* 对比总体指标
*/
private function compareOverallMetrics($baseline, $current) {
$metrics = [
'response_time' => [
'baseline' => $baseline['avg_response_time'],
'current' => $current['avg_response_time'],
'change' => $this->calculateChange(
$baseline['avg_response_time'],
$current['avg_response_time']
),
'status' => $this->determineStatus(
$baseline['avg_response_time'],
$current['avg_response_time'],
10 // 允许10%的变化
)
],
'memory_usage' => [
'baseline' => $baseline['memory_usage'],
'current' => $current['memory_usage'],
'change' => $this->calculateChange(
$baseline['memory_usage'],
$current['memory_usage']
),
'status' => $this->determineStatus(
$baseline['memory_usage'],
$current['memory_usage'],
15
)
]
];
return $metrics;
}
/**
* 检测性能退化
*/
private function detectDegradations($baseline, $current) {
$degradations = [];
$threshold = 10; // 10%退化阈值
foreach ($baseline as $metric => $value) {
if (isset($current[$metric])) {
$change = $this->calculateChange($value, $current[$metric]);
if ($change > $threshold) {
$degradations[] = [
'metric' => $metric,
'baseline' => $value,
'current' => $current[$metric],
'change_percent' => $change,
'severity' => $change > 20 ? 'critical' : 'warning'
];
}
}
}
return $degradations;
}
/**
* 生成优化建议
*/
private function generateRecommendations($baseline, $current) {
$recommendations = [];
// 检查响应时间
if ($current['avg_response_time'] > $baseline['avg_response_time'] * 1.2) {
$recommendations[] = [
'type' => 'performance',
'component' => 'response_time',
'severity' => 'high',
'suggestion' => '考虑优化数据库查询或添加缓存层'
];
}
// 检查内存使用
if ($current['memory_usage'] > memory_get_peak_usage(true) * 0.8) {
$recommendations[] = [
'type' => 'resource',
'component' => 'memory',
'severity' => 'medium',
'suggestion' => '检查是否有内存泄漏,考虑优化数据处理'
];
}
return $recommendations;
}
}
3 报告生成器
<?php
// ReportGenerator.php
use PhpOffice\PhpWord\PhpWord;
use PhpOffice\PhpWord\IOFactory;
use PhpOffice\PhpWord\Style\Table;
class ReportGenerator {
private $analyzer;
private $template;
public function __construct() {
$this->analyzer = new PerformanceAnalyzer();
$this->template = new PhpWord();
}
/**
* 生成HTML报告
*/
public function generateHtmlReport($projectId, $baselineVersion, $currentVersion) {
$comparison = $this->analyzer->generateComparisonReport(
$projectId,
$baselineVersion,
$currentVersion
);
$html = $this->buildHtmlTemplate($comparison);
file_put_contents("reports/{$projectId}_performance_report.html", $html);
return $html;
}
/**
* 生成PDF报告
*/
public function generatePdfReport($projectId, $baselineVersion, $currentVersion) {
$comparison = $this->analyzer->generateComparisonReport(
$projectId,
$baselineVersion,
$currentVersion
);
$pdf = new \TCPDF();
$pdf->AddPage();
$pdf->SetFont('helvetica', 'B', 16);
$pdf->Cell(0, 10, "Performance Comparison Report", 0, 1, 'C');
// 添加概览
$pdf->SetFont('helvetica', '', 12);
$pdf->Ln(10);
$pdf->Cell(0, 10, "Project: {$projectId}", 0, 1);
$pdf->Cell(0, 10, "Baseline Version: {$baselineVersion}", 0, 1);
$pdf->Cell(0, 10, "Current Version: {$currentVersion}", 0, 1);
// 添加详细对比
$this->addComparisonTable($pdf, $comparison);
$pdf->Output("reports/{$projectId}_performance_report.pdf", 'F');
}
/**
* 构建HTML模板
*/
private function buildHtmlTemplate($comparison) {
$html = <<<HTML
<!DOCTYPE html>
<html>
<head>Performance Comparison Report</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.header { background: #2c3e50; color: white; padding: 20px; }
.metric-card { border: 1px solid #ddd; margin: 10px 0; padding: 15px; }
.improvement { color: green; }
.degradation { color: red; }
.warning { color: orange; }
table { width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
th { background-color: #f2f2f2; }
</style>
</head>
<body>
<div class="header">
<h1>Performance Comparison Report</h1>
<p>Generated: {$this->generateTimestamp()}</p>
</div>
<h2>Summary</h2>
{$this->renderSummary($comparison['summary'])}
<h2>Endpoint Comparison</h2>
{$this->renderEndpointComparison($comparison['endpoints'])}
<h2>Degradations</h2>
{$this->renderDegradations($comparison['degradations'])}
<h2>Recommendations</h2>
{$this->renderRecommendations($comparison['recommendations'])}
</body>
</html>
HTML;
return $html;
}
/**
* 渲染概要
*/
private function renderSummary($summary) {
$html = '<div class="metrics-container">';
foreach ($summary as $metric => $data) {
$statusClass = $data['status'] == 'improved' ? 'improvement' :
($data['status'] == 'degraded' ? 'degradation' : 'warning');
$html .= "<div class='metric-card'>
<h3>" . ucfirst(str_replace('_', ' ', $metric)) . "</h3>
<p>Baseline: {$data['baseline']}</p>
<p>Current: {$data['current']}</p>
<p class='{$statusClass}'>Change: {$data['change']}%</p>
<p>Status: <span class='{$statusClass}'>{$data['status']}</span></p>
</div>";
}
$html .= '</div>';
return $html;
}
}
4 自动化调度器
<?php
// Scheduler.php
class PerformanceReportScheduler {
private $reportGenerator;
public function __construct() {
$this->reportGenerator = new ReportGenerator();
}
/**
* 定时生成报告
*/
public function scheduleDailyReport() {
// 获取所有活跃项目
$projects = $this->getActiveProjects();
foreach ($projects as $project) {
try {
// 获取最新两个版本
$baseline = $this->getPreviousVersion($project['id']);
$current = $this->getCurrentVersion($project['id']);
// 生成报告
$htmlReport = $this->reportGenerator->generateHtmlReport(
$project['id'],
$baseline,
$current
);
// 发送通知
$this->sendReportNotification($project, $htmlReport);
// 记录日志
$this->logReportGeneration($project['id'], 'success');
} catch (Exception $e) {
$this->logReportGeneration($project['id'], 'failed', $e->getMessage());
}
}
}
/**
* 部署时的自动对比
*/
public function deployComparison($projectId, $oldVersion, $newVersion) {
echo "Starting performance comparison for deployment...\n";
// 生成对比报告
$report = $this->reportGenerator->generatePdfReport(
$projectId,
$oldVersion,
$newVersion
);
echo "Report generated: reports/{$projectId}_performance_report.pdf\n";
// 检查是否存在严重退化
$degradations = $this->checkCriticalDegradations($projectId);
if (!empty($degradations)) {
echo "WARNING: Critical performance degradations detected!\n";
print_r($degradations);
// 发送告警
$this->sendAlert($projectId, $degradations);
}
return $report;
}
/**
* CI/CD集成
*/
public function ciCdIntegration($projectId, $version) {
// 采集性能数据
$collector = new PerformanceCollector();
$metrics = $collector->collectMetrics($projectId, $version);
// 与历史数据对比
$analysis = $this->analyzer->generateComparisonReport(
$projectId,
$this->getLastStableVersion($projectId),
$version
);
// 根据结果决定是否继续部署
$decision = $this->evaluateDeploymentDecision($analysis);
return [
'passed' => $decision['passed'],
'report' => $analysis,
'message' => $decision['message']
];
}
}
5 可视化图表生成
<?php
// ChartGenerator.php
use CpChart\Data;
use CpChart\Image;
class ChartGenerator {
/**
* 生成性能趋势图
*/
public function generateTrendChart($historicalData, $metric) {
$data = new Data();
foreach ($historicalData as $point) {
$data->addPoints($point['value'], $metric);
$data->addPoints(date('Y-m-d', $point['timestamp']), 'Date');
}
$data->setAbscissa('Date');
$image = new Image(700, 400, $data);
$image->drawLineChart();
$filename = "charts/{$metric}_trend.png";
$image->render($filename);
return $filename;
}
/**
* 生成对比柱状图
*/
public function generateComparisonChart($baseline, $current) {
$data = new Data();
$data->addPoints($baseline, 'Baseline');
$data->addPoints($current, 'Current');
$data->addPoints(array_keys($baseline), 'Metrics');
$data->setAbscissa('Metrics');
$image = new Image(800, 400, $data);
$image->drawBarChart();
$filename = "charts/comparison_chart.png";
$image->render($filename);
return $filename;
}
}
配置与部署
1 配置文件
# config/performance.yml
performance:
collection:
interval: 3600 # 采集间隔(秒)
endpoints:
- /api/users
- /api/products
- /api/orders
analysis:
thresholds:
response_time: 200 # ms
memory_usage: 128 # MB
error_rate: 1 # %
degradation_threshold: 10 # %变化阈值
reports:
output_path: /var/www/reports
formats:
- html
- pdf
retention_days: 30
notifications:
email:
enabled: true
recipients:
- team@example.com
smtp:
host: smtp.example.com
port: 587
slack:
enabled: false
webhook_url: "https://hooks.slack.com/services/..."
2 Crontab配置
# 每小时采集性能数据 0 * * * * /usr/bin/php /var/www/collect_performance.php # 每天生成性能报告 0 6 * * * /usr/bin/php /var/www/generate_daily_report.php # 每周生成详细对比分析 0 7 * * 1 /usr/bin/php /var/www/generate_weekly_comparison.php
使用示例
1 手动生成报告
php generate_report.php project=myapp baseline=v1.0.0 current=v2.0.0 format=pdf
2 CI/CD集成示例
# .gitlab-ci.yml
performance_test:
stage: test
script:
- composer install
- php artisan performance:collect
- php artisan performance:compare
- php artisan performance:generate-report
artifacts:
paths:
- reports/
最佳实践
- 数据采集:使用XHProf或Blackfire进行详细分析
- 基准测试:保留多个版本的基准数据
- 自动化:集成到CI/CD流程中
- 告警机制:设置性能退化告警阈值
- 可视化:使用图表直观展示趋势
- 报告分发:自动发送邮件或推送到协作平台
这个系统可以自动采集、分析并生成性能对比文档,帮助团队及时发现和解决性能问题。