文章目录[隐藏]
WordPress柔性供应链中的实时产能状态监控看板开发教程
引言:柔性供应链管理的数字化需求
在当今快速变化的市场环境中,柔性供应链管理已成为企业保持竞争力的关键。WordPress作为全球最流行的内容管理系统,不仅适用于网站建设,还可以通过定制开发实现企业级应用。本文将详细介绍如何在WordPress中开发一个实时产能状态监控看板,帮助企业实时掌握供应链各环节的产能状况,实现更敏捷的生产调度和资源分配。
系统架构设计
技术栈选择
- WordPress作为基础平台
- MySQL数据库存储产能数据
- REST API实现前后端数据交互
- JavaScript(Vue.js/React)构建交互式前端
- PHP处理后端逻辑
数据库设计
我们需要创建几个核心数据表来存储产能相关信息:
-- 创建产能监控相关数据表
CREATE TABLE wp_capacity_monitor (
id INT AUTO_INCREMENT PRIMARY KEY,
production_line VARCHAR(100) NOT NULL, -- 生产线名称
product_type VARCHAR(100) NOT NULL, -- 产品类型
current_capacity INT DEFAULT 0, -- 当前产能
max_capacity INT DEFAULT 0, -- 最大产能
status ENUM('正常', '繁忙', '空闲', '故障') DEFAULT '空闲', -- 生产线状态
last_updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, -- 最后更新时间
operator_id INT, -- 操作员ID
notes TEXT -- 备注信息
);
CREATE TABLE wp_capacity_history (
id INT AUTO_INCREMENT PRIMARY KEY,
monitor_id INT NOT NULL, -- 关联监控记录ID
recorded_capacity INT NOT NULL, -- 记录的产能值
record_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, -- 记录时间
FOREIGN KEY (monitor_id) REFERENCES wp_capacity_monitor(id) ON DELETE CASCADE
);
后端开发:创建产能监控API
1. 注册自定义REST API端点
<?php
/**
* WordPress产能监控看板 - REST API端点
*/
// 注册产能监控相关的REST API路由
add_action('rest_api_init', function() {
// 获取所有生产线产能状态
register_rest_route('capacity-monitor/v1', '/production-lines', [
'methods' => 'GET',
'callback' => 'get_production_lines_status',
'permission_callback' => function() {
return current_user_can('manage_options'); // 仅管理员可访问
}
]);
// 更新特定生产线产能
register_rest_route('capacity-monitor/v1', '/update-capacity/(?P<id>d+)', [
'methods' => 'POST',
'callback' => 'update_production_capacity',
'permission_callback' => function() {
return current_user_can('edit_posts'); // 编辑权限以上用户可访问
}
]);
// 获取产能历史数据
register_rest_route('capacity-monitor/v1', '/capacity-history/(?P<id>d+)', [
'methods' => 'GET',
'callback' => 'get_capacity_history',
'permission_callback' => function() {
return current_user_can('read'); // 所有登录用户可访问
}
]);
});
/**
* 获取所有生产线产能状态
*/
function get_production_lines_status($request) {
global $wpdb;
$table_name = $wpdb->prefix . 'capacity_monitor';
$results = $wpdb->get_results(
"SELECT * FROM $table_name ORDER BY last_updated DESC"
);
// 计算产能利用率百分比
foreach ($results as $result) {
if ($result->max_capacity > 0) {
$result->utilization_rate = round(($result->current_capacity / $result->max_capacity) * 100, 2);
} else {
$result->utilization_rate = 0;
}
// 根据利用率确定状态颜色
$utilization = $result->utilization_rate;
if ($utilization >= 90) {
$result->status_color = 'danger';
} elseif ($utilization >= 70) {
$result->status_color = 'warning';
} elseif ($utilization >= 40) {
$result->status_color = 'info';
} else {
$result->status_color = 'success';
}
}
return rest_ensure_response($results);
}
/**
* 更新生产线产能
*/
function update_production_capacity($request) {
global $wpdb;
$id = $request['id'];
$current_capacity = $request->get_param('current_capacity');
$status = $request->get_param('status');
$operator_id = get_current_user_id();
$notes = $request->get_param('notes');
$table_name = $wpdb->prefix . 'capacity_monitor';
// 更新生产线数据
$result = $wpdb->update(
$table_name,
[
'current_capacity' => $current_capacity,
'status' => $status,
'operator_id' => $operator_id,
'notes' => $notes
],
['id' => $id]
);
// 记录到历史表
if ($result !== false) {
$history_table = $wpdb->prefix . 'capacity_history';
$wpdb->insert(
$history_table,
[
'monitor_id' => $id,
'recorded_capacity' => $current_capacity
]
);
return rest_ensure_response([
'success' => true,
'message' => '产能数据更新成功'
]);
}
return rest_ensure_response([
'success' => false,
'message' => '产能数据更新失败'
], 500);
}
?>
前端开发:实时监控看板界面
2. 创建Vue.js监控看板组件
<!-- WordPress产能监控看板前端组件 -->
<div id="capacity-monitor-dashboard">
<div class="dashboard-header">
<h1>柔性供应链实时产能监控看板</h1>
<div class="last-updated">最后更新: {{ lastUpdateTime }}</div>
</div>
<div class="dashboard-controls">
<button @click="refreshData" class="btn-refresh">
<span class="dashicons dashicons-update"></span> 刷新数据
</button>
<div class="auto-refresh">
<label>
<input type="checkbox" v-model="autoRefresh"> 自动刷新 (每30秒)
</label>
</div>
</div>
<!-- 状态概览卡片 -->
<div class="status-overview">
<div class="status-card" v-for="line in productionLines" :key="line.id">
<div class="card-header" :class="'status-' + line.status_color">
<h3>{{ line.production_line }}</h3>
<span class="status-badge">{{ line.status }}</span>
</div>
<div class="card-body">
<div class="capacity-info">
<div class="capacity-meter">
<div class="meter-label">产能利用率</div>
<div class="meter-container">
<div class="meter-bar"
:style="{ width: line.utilization_rate + '%' }"
:class="'meter-' + line.status_color">
</div>
</div>
<div class="meter-value">{{ line.utilization_rate }}%</div>
</div>
<div class="capacity-numbers">
<div class="number-item">
<div class="number-label">当前产能</div>
<div class="number-value">{{ line.current_capacity }}</div>
</div>
<div class="number-item">
<div class="number-label">最大产能</div>
<div class="number-value">{{ line.max_capacity }}</div>
</div>
</div>
</div>
<div class="product-info">
<span class="product-type">{{ line.product_type }}</span>
<span class="update-time">更新: {{ formatTime(line.last_updated) }}</span>
</div>
<div class="card-actions" v-if="userCanEdit">
<button class="btn-update" @click="openUpdateModal(line)">
更新产能
</button>
</div>
</div>
</div>
</div>
<!-- 产能更新模态框 -->
<div class="modal" v-if="showUpdateModal">
<div class="modal-content">
<h2>更新产能数据 - {{ selectedLine.production_line }}</h2>
<div class="form-group">
<label>当前产能:</label>
<input type="number" v-model="updateData.current_capacity"
:max="selectedLine.max_capacity" min="0">
<div class="hint">最大产能: {{ selectedLine.max_capacity }}</div>
</div>
<div class="form-group">
<label>状态:</label>
<select v-model="updateData.status">
<option value="正常">正常</option>
<option value="繁忙">繁忙</option>
<option value="空闲">空闲</option>
<option value="故障">故障</option>
</select>
</div>
<div class="form-group">
<label>备注:</label>
<textarea v-model="updateData.notes" rows="3"></textarea>
</div>
<div class="modal-actions">
<button @click="submitUpdate" class="btn-primary">提交更新</button>
<button @click="closeUpdateModal" class="btn-secondary">取消</button>
</div>
</div>
</div>
</div>
<script>
// Vue.js产能监控看板应用
new Vue({
el: '#capacity-monitor-dashboard',
data: {
productionLines: [],
lastUpdateTime: '',
autoRefresh: true,
showUpdateModal: false,
selectedLine: {},
updateData: {
current_capacity: 0,
status: '正常',
notes: ''
},
userCanEdit: true, // 根据用户权限动态设置
refreshInterval: null
},
mounted() {
this.loadData();
this.startAutoRefresh();
},
methods: {
// 加载产能数据
async loadData() {
try {
const response = await fetch('/wp-json/capacity-monitor/v1/production-lines', {
headers: {
'X-WP-Nonce': capacityMonitor.nonce // WordPress安全随机数
}
});
if (response.ok) {
this.productionLines = await response.json();
this.lastUpdateTime = new Date().toLocaleTimeString();
}
} catch (error) {
console.error('加载数据失败:', error);
}
},
// 刷新数据
refreshData() {
this.loadData();
},
// 开始自动刷新
startAutoRefresh() {
if (this.autoRefresh) {
this.refreshInterval = setInterval(() => {
this.loadData();
}, 30000); // 每30秒刷新一次
}
},
// 停止自动刷新
stopAutoRefresh() {
if (this.refreshInterval) {
clearInterval(this.refreshInterval);
this.refreshInterval = null;
}
},
// 打开更新模态框
openUpdateModal(line) {
this.selectedLine = {...line};
this.updateData = {
current_capacity: line.current_capacity,
status: line.status,
notes: line.notes || ''
};
this.showUpdateModal = true;
},
// 关闭更新模态框
closeUpdateModal() {
this.showUpdateModal = false;
this.selectedLine = {};
this.updateData = {
current_capacity: 0,
status: '正常',
notes: ''
};
},
// 提交产能更新
async submitUpdate() {
try {
const response = await fetch(`/wp-json/capacity-monitor/v1/update-capacity/${this.selectedLine.id}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': capacityMonitor.nonce
},
body: JSON.stringify(this.updateData)
});
const result = await response.json();
if (result.success) {
alert('产能数据更新成功!');
this.closeUpdateModal();
this.loadData(); // 重新加载数据
} else {
alert('更新失败: ' + result.message);
}
} catch (error) {
console.error('更新失败:', error);
alert('更新过程中发生错误');
}
},
// 格式化时间显示
formatTime(timestamp) {
const date = new Date(timestamp);
return date.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
});
}
},
watch: {
autoRefresh(newVal) {
if (newVal) {
this.startAutoRefresh();
} else {
this.stopAutoRefresh();
}
}
},
beforeDestroy() {
this.stopAutoRefresh();
}
});
</script>
<style>
/* 产能监控看板样式 */
#capacity-monitor-dashboard {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, sans-serif;
padding: 20px;
}
.dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
padding-bottom: 15px;
border-bottom: 2px solid #007cba;
}
.status-overview {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
gap: 20px;
margin-top: 20px;
}
.status-card {
background: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.card-header {
padding: 15px 20px;
color: white;
}
.status-success { background: #4CAF50; }
.status-info { background: #2196F3; }
.status-warning { background: #FF9800; }
.status-danger { background: #F44336; }
.status-badge {
float: right;
background: rgba(255, 255, 255, 0.2);
padding: 3px 10px;
border-radius: 12px;
font-size: 0.9em;
}
.card-body {
padding: 20px;
}
.capacity-meter {
margin-bottom: 15px;
}
.meter-container {
height: 20px;
background: #f0f0f0;
border-radius: 10px;
overflow: hidden;
margin: 5px 0;
}
.meter-bar {
height: 100%;
transition: width 0.5s ease;
}
.capacity-numbers {
display: flex;
justify-content: space-between;
margin-top: 15px;
}
.number-item {
text-align: center;
}
.number-label {
font-size: 0.9em;
color: #666;
}
.number-value {
font-size: 1.5em;
font-weight: bold;
color: #333;
}
/* 模态框样式 */
.modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.modal-content {
background: white;
padding: 30px;
border-radius: 8px;
max-width: 500px;
width: 90%;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: bold;
}
.form-group input,
.form-group select,
.form-group textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
border-radius: 4px;
}
.modal-actions {
display: flex;
justify-content: flex-end;
gap: 10px;
margin-top: 20px;
}
.btn-primary {
background: #007cba;
color: white;
border: none;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
.btn-secondary {
background: #f0f0f0;
border: 1px solid #ddd;
padding: 10px 20px;
border-radius: 4px;
cursor: pointer;
}
</style>
数据可视化与报警功能
3. 添加实时图表和报警系统
/**
* 产能趋势图表组件
*/
class CapacityChart {
constructor(containerId, lineId) {
this.container = document.getElementById(containerId);
this.lineId = lineId;
this.chart = null;
this.initChart();
}
async initChart() {
// 获取历史数据
const historyData = await this.fetchHistoryData();
// 使用Chart.js创建图表
const ctx = this.container.getContext('2d');
this.chart = new Chart(ctx, {
type: 'line',
data: {
labels: historyData.labels,
datasets: [{
label: '产能趋势',
data: historyData.values,
borderColor: '#007cba',
backgroundColor: 'rgba(0, 124, 186, 0.1)',
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: true
}
},
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '产能值'
}
},
x: {
title: {
续上:
display: true,
text: '时间'
}
}
}
}
});
}
async fetchHistoryData() {
try {
const response = await fetch(
`/wp-json/capacity-monitor/v1/capacity-history/${this.lineId}`
);
const data = await response.json();
// 处理数据格式
return {
labels: data.map(item =>
new Date(item.record_time).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit'
})
),
values: data.map(item => item.recorded_capacity)
};
} catch (error) {
console.error('获取历史数据失败:', error);
return { labels: [], values: [] };
}
}
updateChart(newData) {
if (this.chart) {
// 添加新数据点
this.chart.data.labels.push(newData.label);
this.chart.data.datasets[0].data.push(newData.value);
// 保持最多20个数据点
if (this.chart.data.labels.length > 20) {
this.chart.data.labels.shift();
this.chart.data.datasets[0].data.shift();
}
this.chart.update();
}
}
}
/**
* 产能报警系统
*/
class CapacityAlertSystem {
constructor() {
this.alerts = [];
this.alertRules = {
highUtilization: 90, // 利用率超过90%报警
lowUtilization: 20, // 利用率低于20%报警
statusChange: true // 状态变化报警
};
}
checkAlerts(productionLine) {
const alerts = [];
// 检查产能利用率
if (productionLine.utilization_rate >= this.alertRules.highUtilization) {
alerts.push({
type: 'high_utilization',
message: `${productionLine.production_line} 产能利用率过高: ${productionLine.utilization_rate}%`,
severity: 'warning',
timestamp: new Date()
});
}
if (productionLine.utilization_rate <= this.alertRules.lowUtilization) {
alerts.push({
type: 'low_utilization',
message: `${productionLine.production_line} 产能利用率过低: ${productionLine.utilization_rate}%`,
severity: 'info',
timestamp: new Date()
});
}
// 检查状态变化
if (productionLine.status === '故障') {
alerts.push({
type: 'equipment_fault',
message: `${productionLine.production_line} 报告设备故障`,
severity: 'critical',
timestamp: new Date()
});
}
return alerts;
}
displayAlerts(alerts) {
const alertContainer = document.getElementById('alert-container');
if (!alertContainer) return;
alertContainer.innerHTML = '';
alerts.forEach(alert => {
const alertElement = document.createElement('div');
alertElement.className = `alert alert-${alert.severity}`;
alertElement.innerHTML = `
<span class="alert-time">${alert.timestamp.toLocaleTimeString()}</span>
<span class="alert-message">${alert.message}</span>
<button class="alert-dismiss">×</button>
`;
alertElement.querySelector('.alert-dismiss').addEventListener('click', () => {
alertElement.remove();
});
alertContainer.appendChild(alertElement);
});
}
}
// 初始化报警系统
const alertSystem = new CapacityAlertSystem();
// 在Vue应用中集成报警功能
Vue.component('alert-panel', {
template: `
<div class="alert-panel">
<h3>实时报警</h3>
<div class="alert-list">
<div v-for="alert in alerts"
:key="alert.timestamp"
:class="['alert-item', 'alert-' + alert.severity]">
<span class="alert-time">{{ formatTime(alert.timestamp) }}</span>
<span class="alert-message">{{ alert.message }}</span>
</div>
<div v-if="alerts.length === 0" class="no-alerts">
当前没有报警信息
</div>
</div>
</div>
`,
data() {
return {
alerts: []
};
},
methods: {
formatTime(timestamp) {
return new Date(timestamp).toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
},
addAlert(alert) {
this.alerts.unshift(alert);
// 保持最多10条报警记录
if (this.alerts.length > 10) {
this.alerts.pop();
}
// 播放报警声音(如果是严重报警)
if (alert.severity === 'critical') {
this.playAlertSound();
}
},
playAlertSound() {
const audio = new Audio('/wp-content/plugins/capacity-monitor/alert.mp3');
audio.play().catch(e => console.log('音频播放失败:', e));
}
}
});
WordPress插件集成
4. 创建完整的WordPress插件
<?php
/**
* Plugin Name: 柔性供应链产能监控看板
* Plugin URI: https://yourwebsite.com/
* Description: 实时监控柔性供应链中各生产线的产能状态
* Version: 1.0.0
* Author: Your Name
* License: GPL v2 or later
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('CAPACITY_MONITOR_VERSION', '1.0.0');
define('CAPACITY_MONITOR_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('CAPACITY_MONITOR_PLUGIN_URL', plugin_dir_url(__FILE__));
// 包含必要文件
require_once CAPACITY_MONITOR_PLUGIN_DIR . 'includes/class-database.php';
require_once CAPACITY_MONITOR_PLUGIN_DIR . 'includes/class-api.php';
require_once CAPACITY_MONITOR_PLUGIN_DIR . 'includes/class-admin.php';
/**
* 主插件类
*/
class Capacity_Monitor_Plugin {
private static $instance = null;
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
$this->init_hooks();
}
private function init_hooks() {
// 激活/停用钩子
register_activation_hook(__FILE__, [$this, 'activate_plugin']);
register_deactivation_hook(__FILE__, [$this, 'deactivate_plugin']);
// 初始化组件
add_action('plugins_loaded', [$this, 'init_components']);
// 添加管理菜单
add_action('admin_menu', [$this, 'add_admin_menu']);
// 注册短代码
add_shortcode('capacity_monitor', [$this, 'render_monitor_shortcode']);
// 注册脚本和样式
add_action('wp_enqueue_scripts', [$this, 'enqueue_frontend_assets']);
add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
}
public function activate_plugin() {
// 创建数据库表
Capacity_Monitor_Database::create_tables();
// 插入示例数据
$this->insert_sample_data();
// 设置默认选项
update_option('capacity_monitor_version', CAPACITY_MONITOR_VERSION);
update_option('capacity_monitor_auto_refresh', 30); // 默认30秒自动刷新
}
public function deactivate_plugin() {
// 清理临时数据
// 注意:不删除数据库表,保留数据
}
public function init_components() {
// 初始化API
Capacity_Monitor_API::init();
// 初始化管理界面
if (is_admin()) {
Capacity_Monitor_Admin::init();
}
}
public function add_admin_menu() {
add_menu_page(
'产能监控看板',
'产能监控',
'manage_options',
'capacity-monitor',
[$this, 'render_admin_page'],
'dashicons-dashboard',
30
);
add_submenu_page(
'capacity-monitor',
'生产线管理',
'生产线管理',
'manage_options',
'capacity-monitor-lines',
[$this, 'render_lines_page']
);
add_submenu_page(
'capacity-monitor',
'报警设置',
'报警设置',
'manage_options',
'capacity-monitor-alerts',
[$this, 'render_alerts_page']
);
}
public function render_admin_page() {
?>
<div class="wrap">
<h1>柔性供应链产能监控看板</h1>
<div id="capacity-monitor-admin-dashboard"></div>
</div>
<?php
}
public function render_monitor_shortcode($atts) {
// 检查用户权限
if (!is_user_logged_in()) {
return '<p>请登录后查看产能监控看板</p>';
}
// 输出前端看板
ob_start();
include CAPACITY_MONITOR_PLUGIN_DIR . 'templates/frontend-dashboard.php';
return ob_get_clean();
}
public function enqueue_frontend_assets() {
// 只在需要时加载
if (!has_shortcode(get_post()->post_content, 'capacity_monitor')) {
return;
}
// 加载Vue.js
wp_enqueue_script('vue', 'https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js', [], '2.6.14');
// 加载Chart.js
wp_enqueue_script('chart-js', 'https://cdn.jsdelivr.net/npm/chart.js@3.5.1/dist/chart.min.js', [], '3.5.1');
// 加载插件主脚本
wp_enqueue_script(
'capacity-monitor-frontend',
CAPACITY_MONITOR_PLUGIN_URL . 'assets/js/frontend.js',
['vue', 'chart-js', 'jquery'],
CAPACITY_MONITOR_VERSION,
true
);
// 加载样式
wp_enqueue_style(
'capacity-monitor-frontend',
CAPACITY_MONITOR_PLUGIN_URL . 'assets/css/frontend.css',
[],
CAPACITY_MONITOR_VERSION
);
// 传递数据到JavaScript
wp_localize_script('capacity-monitor-frontend', 'capacityMonitor', [
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('capacity_monitor_nonce'),
'api_base' => rest_url('capacity-monitor/v1'),
'auto_refresh' => get_option('capacity_monitor_auto_refresh', 30)
]);
}
public function enqueue_admin_assets($hook) {
if (strpos($hook, 'capacity-monitor') === false) {
return;
}
// 加载管理界面脚本和样式
wp_enqueue_script(
'capacity-monitor-admin',
CAPACITY_MONITOR_PLUGIN_URL . 'assets/js/admin.js',
['jquery', 'wp-api'],
CAPACITY_MONITOR_VERSION,
true
);
wp_enqueue_style(
'capacity-monitor-admin',
CAPACITY_MONITOR_PLUGIN_URL . 'assets/css/admin.css',
[],
CAPACITY_MONITOR_VERSION
);
}
private function insert_sample_data() {
global $wpdb;
$table_name = $wpdb->prefix . 'capacity_monitor';
$sample_data = [
[
'production_line' => 'A生产线',
'product_type' => '电子产品',
'current_capacity' => 85,
'max_capacity' => 100,
'status' => '繁忙'
],
[
'production_line' => 'B生产线',
'product_type' => '机械零件',
'current_capacity' => 45,
'max_capacity' => 80,
'status' => '正常'
],
[
'production_line' => 'C生产线',
'product_type' => '塑料制品',
'current_capacity' => 20,
'max_capacity' => 50,
'status' => '空闲'
]
];
foreach ($sample_data as $data) {
$wpdb->insert($table_name, $data);
}
}
}
// 初始化插件
Capacity_Monitor_Plugin::get_instance();
?>
系统优化与扩展
5. 性能优化和安全增强
<?php
/**
* 数据库优化类
*/
class Capacity_Monitor_Optimizer {
/**
* 清理历史数据
*/
public static function cleanup_old_data($days_to_keep = 30) {
global $wpdb;
$history_table = $wpdb->prefix . 'capacity_history';
$cutoff_date = date('Y-m-d H:i:s', strtotime("-$days_to_keep days"));
$result = $wpdb->query(
$wpdb->prepare(
"DELETE FROM $history_table WHERE record_time < %s",
$cutoff_date
)
);
return $result;
}
/**
* 添加数据库索引优化查询性能
*/
public static function add_indexes() {
global $wpdb;
$monitor_table = $wpdb->prefix . 'capacity_monitor';
$history_table = $wpdb->prefix . 'capacity_history';
$indexes = [
"ALTER TABLE $monitor_table ADD INDEX idx_status (status)",
"ALTER TABLE $monitor_table ADD INDEX idx_last_updated (last_updated)",
"ALTER TABLE $history_table ADD INDEX idx_record_time (record_time)",
"ALTER TABLE $history_table ADD INDEX idx_monitor_id (monitor_id)"
];
foreach ($indexes as $sql) {
$wpdb->query($sql);
}
}
/**
* 数据缓存机制
*/
public static function get_cached_data($key, $callback, $expiration = 300) {
$cached = wp_cache_get($key, 'capacity_monitor');
if (false === $cached) {
$cached = call_user_func($callback);
wp_cache_set($key, $cached, 'capacity_monitor', $expiration);
}
return $cached;
}
}
/**
* 安全增强类
*/
class Capacity_Monitor_Security {
/**
* 验证用户权限
*/
public static function check_permission($capability = 'read') {
if (!is_user_logged_in()) {
return new WP_Error('unauthorized', '用户未登录', ['status' => 401]);
}
if (!current_user_can($capability)) {
return new WP_Error('forbidden', '权限不足', ['status' => 403]);
}
return true;
}
/**
* 输入数据验证
*/
public static function validate_input($data, $rules) {
$errors = [];
foreach ($rules as $field => $rule) {
if (!isset($data[$field])) {
$errors[$field] = '字段不存在';
continue;
}
$value = $data[$field];
// 必填检查
if (isset($rule['required']) && $rule['required'] && empty($value)) {
$errors[$field] = '该字段为必填项';
continue;
}
// 类型检查
if (isset($rule['type'])) {
switch ($rule['type']) {
case 'integer':
if (!is_numeric($value)) {
$errors[$field] = '必须为整数';
}
break;
case 'string':
if (!is_string($value)) {
$errors[$field] = '必须为字符串';
}
break;
case 'enum':
if (!in_array($value, $rule['values'])) {
$errors[$field] = '无效的值';
}
break;
}
}
// 范围检查
if (isset($rule['min']) && $value < $rule['min']) {
$errors[$field] = "最小值不能小于{$rule['min']}";
}
if (isset($rule['max']) && $value > $rule['max']) {
$errors[$field] = "最大值不能大于{$rule['max']}";
}
}
return empty($errors) ? true : $errors;
}
/**
* 防止SQL注入
*/
public static function sanitize_sql($input) {
global $wpdb;
if (is_array($input)) {
return array_map([$wpdb, '_escape'], $input);
}
return $wpdb->_escape($input);
}
/**
* 记录操作日志
*/
public static function log_operation($user_id, $action, $details) {
global $wpdb;
$table_name = $wpdb->prefix . 'capacity_monitor_logs';
$wpdb->insert($table_name, [
'user_id' => $user_id,
'action' => $action,
'details' => json_encode($details),
'ip_address' => $_SERVER['REMOTE_ADDR'],
'user_agent' => $_SERVER['HTTP_USER_AGENT'],
'created_at' => current_time('mysql')
]);
}
}
?>
部署与维护
6. 部署指南和维护建议
# 部署指南
## 系统要求
- WordPress 5.6+
- PHP 7.4+
- MySQL 5.7+
- 至少256MB内存


