PHP 开发
针对当前 PHP 8.x 版本、PHPUnit 11+、Composer 2.x 以及基于 PDO 的 MySQL 或 MariaDB 应用程序进行了优化。
关于使用 PHP 8.0+、PDO 进行安全数据库访问、RESTful API 设计和 XAMPP 环境配置构建高质量 PHP 应用程序的专家指导,参考官方 PHP 文档 https://php.net。
- 在可用时利用原生并行子代理分发和 200k+ 上下文窗口。
跨客户端可移植性
本技能编写为在 GitHub Copilot、Claude Code 和 Codex 中均可使用。
- GitHub Copilot:将文件夹保存在 Copilot 可见的技能路径中,或者当文件夹发现不可用时,将工作流包装在项目指令中。
- Claude Code:将文件夹保存在本地技能目录或兼容的插件源中。
- Codex:将文件夹安装或同步到
$CODEX_HOME/skills/php-development,并在重大更改后重新启动 Codex。
MCP 可用性和回退
首选 MCP 服务器:无要求
- 回退提示:“在没有 MCP 的情况下使用 PHP 开发技能。依赖其本地指令、捆绑资源、标准 shell 或编辑器工具以及直接验证。在得出结论之前显示所使用的证据。”
- 当活动主机未暴露 MCP 操作时,不要声称使用了 MCP 操作。
- 将本地文件、测试、渲染输出、日志或屏幕截图视为回退证据路径。
反模式
- 直接插值 SQL:预处理语句是 PHP 数据访问正确性和安全性的基准。
- 混合请求解析、业务规则和渲染:紧密耦合的脚本更难测试和演变为 API。
- 假设验证可以防止 XSS:当用户控制的内容被渲染回 HTML 时,输出编码仍然很重要。
验证协议
在声称“技能应用成功”之前:
- 通过/失败:PHP 开发实现应标明目标运行时、框架版本和受影响的文件。
- 通过/失败:对更改的表面运行构建、lint、测试或等效的本地验证。
- 通过/失败:处理或明确排除错误、依赖漂移和环境差异的边界情况。
- 压力测试场景:将工作流应用于一个通过快乐路径测试但失败一个边界条件的更改。
- 成功指标:零个未经测试的成功声明;每个实现声明都对应一个命令或工件。
前后示例
<?php
// 之前
$stmt = $pdo->query("SELECT * FROM users WHERE email = '$email'");
$user = $stmt->fetch();
// 之后
$stmt = $pdo->prepare('SELECT id, email, password_hash FROM users WHERE email = :email LIMIT 1');
$stmt->execute(['email' => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
用预处理语句和更窄的结果形状替换字符串插值。
激活条件
使用症状 -> 动作触发器:当匹配时,应用此技能并使用下面的协议进行验证。
核心 PHP 开发:
- 使用适当的 HTTP 方法构建 PHP RESTful API
- 处理 XAMPP(Apache + MySQL + PHP)环境
- 使用 PDO 实现安全数据库操作
- 创建身份验证和会话管理系统
- 处理文件上传和表单提交
数据库和数据层:
- 使用 PDO 将 PHP 连接到 MySQL/MariaDB
- 编写预处理语句以防止 SQL 注入
- 实现事务处理以确保数据完整性
- 创建用于数据访问的存储库模式
- MySQLi 与 PDO 的比较
安全与最佳实践:
- 实现密码哈希(password_hash, password_verify)
- 防范 XSS、CSRF 和 SQL 注入
- 验证和清理用户输入
- 管理会话和身份验证令牌
- 配置 API 访问的 CORS 标头
API 开发:
- 使用正确的 HTTP 状态码设计 RESTful 端点
- 处理 JSON 请求和响应
- 实现用于身份验证和授权的中间件
- 错误处理和日志记录
- 速率限制和 API 版本控制
第 1 部分:PHP 8.0+ 基础知识
现代 PHP 特性
<?php
// 命名参数 (PHP 8.0+)
function createUser(string $name, string $email, bool $isAdmin = false): User {
return new User($name, $email, $isAdmin);
}
// 使用命名参数调用
$user = createUser(email: '[email protected]', name: 'John Doe');
// 联合类型 (PHP 8.0+)
function processValue(string|int|float $value): string {
return (string)$value;
}
// 空安全运算符 (PHP 8.0+)
$country = $session?->user?->address?->country ?? 'Unknown';
// 构造函数属性提升 (PHP 8.0+)
class User {
public function __construct(
public string $name,
public string $email,
private string $passwordHash
) {}
}
类型声明和严格类型
<?php
declare(strict_types=1); // 强制类型安全
// 类型化属性和返回类型
class Recipe {
private int $id;
private string $title;
private ?DateTime $createdAt;
public function __construct(int $id, string $title) {
$this->id = $id;
$this->title = $title;
}
public function getTitle(): string {
return $this->title;
}
public function setCreatedAt(?DateTime $date): void {
$this->createdAt = $date;
}
}
// 联合和交集类型
function processData(string|array $data): string|int {
return is_array($data) ? count($data) : strlen($data);
}
第 2 部分:PDO 数据库集成
数据库连接类
<?php
class Database {
private static ?PDO $instance = null;
public static function getInstance(): PDO {
if (self::$instance === null) {
$host = $_ENV['DB_HOST'] ?? 'localhost';
$dbname = $_ENV['DB_NAME'] ?? 'recipe_sharing_system';
$username = $_ENV['DB_USER'] ?? 'root';
$password = $_ENV['DB_PASSWORD'] ?? '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$dbname;charset=$charset";
try {
self::$instance = new PDO($dsn, $username, $password, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
} catch (PDOException $e) {
error_log("数据库连接失败:" . $e->getMessage());
throw new RuntimeException("数据库连接错误");
}
}
return self::$instance;
}
}
用于安全的预处理语句
<?php
class UserRepository {
private PDO $db;
public function __construct(PDO $db) {
$this->db = $db;
}
// 使用预处理语句通过电子邮件查找用户
public function findByEmail(string $email): ?array {
$stmt = $this->db->prepare(
"SELECT id, email, password_hash, role, status
FROM user
WHERE email = :email LIMIT 1"
);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->execute();
$user = $stmt->fetch();
return $user ?: null;
}
// 使用密码哈希创建新用户
public function create(string $name, string $email, string $password): int {
$passwordHash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $this->db->prepare(
"INSERT INTO user (name, email, password_hash, role, status, created_at, updated_at)
VALUES (:name, :email, :password_hash, 'user', 'active', NOW(), NOW())"
);
$stmt->bindParam(':name', $name, PDO::PARAM_STR);
$stmt->bindParam(':email', $email, PDO::PARAM_STR);
$stmt->bindParam(':password_hash', $passwordHash, PDO::PARAM_STR);
$stmt->execute();
return (int) $this->db->lastInsertId();
}
// 使用密码验证的身份验证
public function authenticate(string $email, string $password): ?array {
$user = $this->findByEmail($email);
if ($user === null) {
return null;
}
if (!password_verify($password, $user['password_hash'])) {
return null;
}
// 检查密码是否需要重新哈希
if (password_needs_rehash($user['password_hash'], PASSWORD_DEFAULT)) {
$newHash = password_hash($password, PASSWORD_DEFAULT);
$this->updatePasswordHash($user['id'], $newHash);
}
unset($user['password_hash']); // 移除敏感数据
return $user;
}
private function updatePasswordHash(int $userId, string $hash): void {
$stmt = $this->db->prepare(
"UPDATE user SET password_hash = :hash WHERE id = :id"
);
$stmt->execute([':hash' => $hash, ':id' => $userId]);
}
}
事务管理
<?php
class RecipeService {
private PDO $db;
public function __construct(PDO $db) {
$this->db = $db;
}
// 在事务中创建包含配料、说明和图片的配方
public function createRecipeWithDetails(array $recipeData, array $ingredients, array $instructions): int {
try {
$this->db->beginTransaction();
// 插入配方
$stmt = $this->db->prepare(
"INSERT INTO recipe (title, description, category, difficulty, prep_time, cook_time, servings, author_id, status, created_at, updated_at)
VALUES (:title, :description, :category, :difficulty, :prep_time, :cook_time, :servings, :author_id, 'pending', NOW(), NOW())"
);
$stmt->execute([
':title' => $recipeData['title'],
':description' => $recipeData['description'],
':category' => $recipeData['category'],
':difficulty' => $recipeData['difficulty'],
':prep_time' => $recipeData['prepTime'],
':cook_time' => $recipeData['cookTime'],
':servings' => $recipeData['servings'],
':author_id' => $recipeData['authorId'],
]);
$recipeId = (int) $this->db->lastInsertId();
// 插入配料
$ingredientStmt = $this->db->prepare(
"INSERT INTO ingredient (recipe_id, name, quantity, unit, sort_order, created_at, updated_at)
VALUES (:recipe_id, :name, :quantity, :unit, :sort_order, NOW(), NOW())"
);
foreach ($ingredients as $index => $ingredient) {
$ingredientStmt->execute([
':recipe_id' => $recipeId,
':name' => $ingredient['name'],
':quantity' => $ingredient['quantity'],
':unit' => $ingredient['unit'],
':sort_order' => $index,
]);
}
// 插入说明
$instructionStmt = $this->db->prepare(
"INSERT INTO instruction (recipe_id, step_number, instruction_text, created_at, updated_at)
VALUES (:recipe_id, :step_number, :instruction_text, NOW(), NOW())"
);
foreach ($instructions as $index => $instruction) {
$instructionStmt->execute([
':recipe_id' => $recipeId,
':step_number' => $index + 1,
':instruction_text' => $instruction['text'],
]);
}
$this->db->commit();
return $recipeId;
} catch (Exception $e) {
$this->db->rollBack();
error_log("创建配方失败:" . $e->getMessage());
throw $e;
}
}
}
第 3 部分:RESTful API 开发
JSON 响应助手
<?php
class Response {
public static function json(mixed $data, int $statusCode = 200): never {
http_response_code($statusCode);
header('Content-Type: application/json; charset=utf-8');
echo json_encode($data, JSON_THROW_ON_ERROR | JSON_UNESCAPED_SLASHES);
exit;
}
public static function error(string $message, int $statusCode = 400): never {
self::json([
'success' => false,
'error' => $message,
], $statusCode);
}
public static function success(mixed $data = null, string $message = '成功'): never {
self::json([
'success' => true,
'message' => $message,
'data' => $data,
]);
}
}
CORS 中间件
<?php
// 处理 CORS 标头
$allowedOrigins = [
'http://localhost:5173', // Vite 开发服务器
'http://localhost:3000', // 替代开发服务器
];
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, $allowedOrigins, true)) {
header("Access-Control-Allow-Origin: $origin");
}
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
// 处理预检请求
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
http_response_code(200);
exit;
}
身份验证中间件
<?php
function requireAuth(): array {
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
if (!preg_match('/Bearer\s+(.*)$/i', $authHeader, $matches)) {
Response::error('未授权:缺少或无效的令牌', 401);
}
$token = $matches[1];
// 验证令牌(示例使用 JWT)
try {
$payload = JWT::decode($token, $_ENV['JWT_SECRET'], ['HS256']);
return (array) $payload;
} catch (Exception $e) {
Response::error('未授权:无效的令牌', 401);
}
}
function requireAdmin(): array {
$user = requireAuth();
if ($user['role'] !== 'admin') {
Response::error('禁止:需要管理员权限', 403);
}
return $user;
}
第 4 部分:XAMPP 环境设置
目录结构
htdocs/
├── project-root/
│ ├── public/ # Web 根目录
│ │ └── index.php
│ ├── src/ # 源代码
│ │ └── ...
│ ├── config/ # 配置文件
│ │ └── database.php
│ ├── vendor/ # Composer 依赖
│ └── .htaccess # Apache 配置
Apache 配置(.htaccess)
RewriteEngine On
RewriteRule ^(.*)$ public/$1 [L]
数据库初始化
CREATE DATABASE IF NOT EXISTS recipe_sharing_system
CHARACTER SET utf8mb4
COLLATE utf8mb4_unicode_ci;
USE recipe_sharing_system;
CREATE TABLE user (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(255) NOT NULL UNIQUE,
password_hash VARCHAR(255) NOT NULL,
role ENUM('user', 'admin') DEFAULT 'user',
status ENUM('active', 'inactive', 'banned') DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
验证检查清单
- PHP 版本 >= 8.0
- 使用
declare(strict_types=1); - 未使用已弃用的 PHP 函数
- PDO 已配置异常模式和关联获取
- 所有数据库查询均使用预处理语句
- 密码使用
password_hash()和password_verify()处理 - API 端点包含 CORS 标头
- 请求和响应使用 JSON 格式
- 错误已正确处理并记录
- 配置从环境变量读取