PHP 開發
針對當前 PHP 8.x 版本、PHPUnit 11+、Composer 2.x 和 PDO 支援的 MySQL 或 MariaDB 應用程式進行最佳化。
提供建構高品質 PHP 應用程式的專業指導,使用 PHP 8.0+、PDO 安全資料庫存取、RESTful API 設計和 XAMPP 環境設定,遵循官方 PHP 文件 (https://php.net)。
- 在可用情況下,利用原生並行子代理分派和 200k+ 上下文視窗。
跨客戶端可攜性
此技能設計為可在 GitHub Copilot、Claude Code 和 Codex 中使用。
- GitHub Copilot:將資料夾放在 Copilot 可識別的技能路徑中,或在資料夾發現不可用時,將工作流程包裝在專案指令中。
- Claude Code:將資料夾放在本機技能目錄或相容的外掛來源中。
- Codex:將資料夾安裝或同步到
$CODEX_HOME/skills/php-development,並在重大變更後重新啟動 Codex。
MCP 可用性與回退
首選 MCP 伺服器:不需要
- 回退提示:「使用 PHP 開發技能,無需 MCP。依賴其本機指令、捆綁資源、標準 shell 或編輯器工具以及直接驗證。在得出結論前,顯示所使用的證據。」
- 當主機未暴露 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 = 'Success'): 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;
}
API 路由範例
<?php
// 簡單的 API 路由
$requestMethod = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// 基本路由
$routes = [
'GET' => [
'/api/users' => 'UserController::index',
'/api/users/{id}' => 'UserController::show',
'/api/recipes' => 'RecipeController::index',
'/api/recipes/{id}' => 'RecipeController::show',
],
'POST' => [
'/api/users' => 'UserController::store',
'/api/recipes' => 'RecipeController::store',
'/api/auth/login' => 'AuthController::login',
'/api/auth/register' => 'AuthController::register',
],
'PUT' => [
'/api/users/{id}' => 'UserController::update',
'/api/recipes/{id}' => 'RecipeController::update',
],
'DELETE' => [
'/api/users/{id}' => 'UserController::destroy',
'/api/recipes/{id}' => 'RecipeController::destroy',
],
];
// 比對路由
$matchedRoute = null;
$params = [];
if (isset($routes[$requestMethod])) {
foreach ($routes[$requestMethod] as $route => $handler) {
// 將 {param} 轉換為正規表達式
$pattern = preg_replace('/\{([a-zA-Z_]+)\}/', '(?P<$1>[^/]+)', $route);
$pattern = '#^' . $pattern . '$#';
if (preg_match($pattern, $requestUri, $matches)) {
$matchedRoute = $handler;
$params = array_filter($matches, 'is_string', ARRAY_FILTER_USE_KEY);
break;
}
}
}
if ($matchedRoute === null) {
Response::error('找不到路由', 404);
}
// 呼叫處理器
[$class, $method] = explode('::', $matchedRoute);
$controller = new $class();
echo $controller->$method($params);
第 4 部分:XAMPP 設定
Apache 虛擬主機設定
<VirtualHost *:80>
ServerName recipe-sharing.local
DocumentRoot "C:/xampp/htdocs/recipe-sharing/public"
<Directory "C:/xampp/htdocs/recipe-sharing/public">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
ErrorLog "C:/xampp/apache/logs/recipe-sharing-error.log"
CustomLog "C:/xampp/apache/logs/recipe-sharing-access.log" combined
</VirtualHost>
.htaccess 重寫規則
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
PHP 錯誤報告設定
<?php
// 開發環境
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// 記錄設定
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/logs/php-error.log');
// 時間區域
date_default_timezone_set('Asia/Taipei');
第 5 部分:安全性與最佳實務
輸入驗證與清理
<?php
class Validator {
// 驗證電子郵件
public static function email(string $email): bool {
return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}
// 清理字串輸出
public static function escape(string $value): string {
return htmlspecialchars($value, ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
// 驗證 URL
public static function url(string $url): bool {
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
// 清理整數
public static function int(mixed $value, int $min = null, int $max = null): ?int {
$filtered = filter_var($value, FILTER_VALIDATE_INT, [
'options' => [
'min_range' => $min ?? PHP_INT_MIN,
'max_range' => $max ?? PHP_INT_MAX,
]
]);
return $filtered !== false ? $filtered : null;
}
// 清理字串
public static function string(mixed $value, int $maxLength = 255): ?string {
if (!is_string($value)) {
return null;
}
$trimmed = trim($value);
if (strlen($trimmed) > $maxLength) {
return null;
}
return $trimmed;
}
}
CSRF 保護
<?php
session_start();
class Csrf {
// 產生 CSRF 權杖
public static function generate(): string {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
// 驗證 CSRF 權杖
public static function validate(string $token): bool {
if (empty($_SESSION['csrf_token'])) {
return false;
}
return hash_equals($_SESSION['csrf_token'], $token);
}
// 重新產生 CSRF 權杖
public static function regenerate(): void {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
}
檔案上傳處理
<?php
class FileUpload {
private array $allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
private int $maxSize = 5242880; // 5MB
private string $uploadDir;
public function __construct(string $uploadDir) {
$this->uploadDir = rtrim($uploadDir, '/') . '/';
if (!is_dir($this->uploadDir)) {
mkdir($this->uploadDir, 0755, true);
}
}
public function upload(array $file): ?string {
// 驗證錯誤
if ($file['error'] !== UPLOAD_ERR_OK) {
throw new RuntimeException('檔案上傳失敗');
}
// 驗證檔案類型
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $file['tmp_name']);
finfo_close($finfo);
if (!in_array($mimeType, $this->allowedTypes, true)) {
throw new RuntimeException('不允許的檔案類型');
}
// 驗證檔案大小
if ($file['size'] > $this->maxSize) {
throw new RuntimeException('檔案太大');
}
// 產生唯一檔名
$extension = pathinfo($file['name'], PATHINFO_EXTENSION);
$filename = bin2hex(random_bytes(16)) . '.' . $extension;
// 移動檔案
if (!move_uploaded_file($file['tmp_name'], $this->uploadDir . $filename)) {
throw new RuntimeException('無法儲存檔案');
}
return $filename;
}
}
第 6 部分:測試與除錯
PHPUnit 測試範例
<?php
use PHPUnit\Framework\TestCase;
class UserRepositoryTest extends TestCase {
private PDO $db;
private UserRepository $repository;
protected function setUp(): void {
// 設定記憶體資料庫
$this->db = new PDO('sqlite::memory:');
$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 建立資料表
$this->db->exec(
"CREATE TABLE user (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'user',
status TEXT DEFAULT 'active',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)"
);
$this->repository = new UserRepository($this->db);
}
public function testCreateUser(): void {
$userId = $this->repository->create('John Doe', '[email protected]', 'securePassword123');
$this->assertIsInt($userId);
$this->assertGreaterThan(0, $userId);
}
public function testFindByEmail(): void {
$this->repository->create('Jane Doe', '[email protected]', 'securePassword456');
$user = $this->repository->findByEmail('[email protected]');
$this->assertNotNull($user);
$this->assertEquals('Jane Doe', $user['name']);
$this->assertEquals('[email protected]', $user['email']);
}
public function testAuthenticateWithValidCredentials(): void {
$email = '[email protected]';
$password = 'validPassword123';
$this->repository->create('Test User', $email, $password);
$result = $this->repository->authenticate($email, $password);
$this->assertNotNull($result);
$this->assertArrayNotHasKey('password_hash', $result);
}
public function testAuthenticateWithInvalidCredentials(): void {
$result = $this->repository->authenticate('[email protected]', 'wrongPassword');
$this->assertNull($result);
}
}
錯誤記錄設定
<?php
class Logger {
private string $logDir;
private string $logFile;
public function __construct(string $logDir = null) {
$this->logDir = $logDir ?? __DIR__ . '/logs';
if (!is_dir($this->logDir)) {
mkdir($this->logDir, 0755, true);
}
$this->logFile = $this->logDir . '/app-' . date('Y-m-d') . '.log';
}
public function info(string $message, array $context = []): void {
$this->log('INFO', $message, $context);
}
public function error(string $message, array $context = []): void {
$this->log('ERROR', $message, $context);
}
public function warning(string $message, array $context = []): void {
$this->log('WARNING', $message, $context);
}
private function log(string $level, string $message, array $context = []): void {
$timestamp = date('Y-m-d H:i:s');
$contextJson = !empty($context) ? json_encode($context, JSON_UNESCAPED_SLASHES) : '';
$logMessage = "[$timestamp] [$level] $message $contextJson" . PHP_EOL;
file_put_contents($this->logFile, $logMessage, FILE_APPEND | LOCK_EX);
}
}
第 7 部分:專案結構與 Composer
建議的專案結構
recipe-sharing/
├── public/
│ ├── index.php # 進入點
│ └── .htaccess # Apache 重寫規則
├── src/
│ ├── Controllers/
│ │ ├── AuthController.php
│ │ ├── RecipeController.php
│ │ └── UserController.php
│ ├── Models/
│ │ ├── User.php
│ │ └── Recipe.php
│ ├── Repositories/
│ │ ├── UserRepository.php
│ │ └── RecipeRepository.php
│ ├── Services/
│ │ ├── AuthService.php
│ │ └── RecipeService.php
│ ├── Middleware/
│ │ ├── AuthMiddleware.php
│ │ └── CorsMiddleware.php
│ ├── Validators/
│ │ └── Validator.php
│ └── Config/
│ ├── database.php
│ └── app.php
├── tests/
│ ├── Unit/
│ │ └── UserRepositoryTest.php
│ └── Feature/
│ └── RecipeApiTest.php
├── logs/
├── vendor/ # Composer 相依性
├── composer.json
├── composer.lock
├── .env # 環境變數
├── .env.example
└── README.md
Composer 設定
{
"name": "recipe-sharing/api",
"description": "Recipe Sharing System API",
"type": "project",
"require": {
"php": ">=8.0",
"ext-pdo": "*",
"ext-json": "*",
"ext-mbstring": "*",
"vlucas/phpdotenv": "^5.5",
"firebase/php-jwt": "^6.0"
},
"require-dev": {
"phpunit/phpunit": "^11.0",
"squizlabs/php_codesniffer": "^3.7"
},
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"test": "phpunit",
"cs": "phpcs",
"cs-fix": "phpcbf"
}
}
環境變數 (.env)
APP_NAME=RecipeSharing
APP_ENV=development
APP_DEBUG=true
APP_URL=http://localhost:8000
DB_HOST=localhost
DB_PORT=3306
DB_NAME=recipe_sharing_system
DB_USER=root
DB_PASSWORD=
JWT_SECRET=your-secret-key-change-in-production
JWT_EXPIRY=3600
CORS_ALLOWED_ORIGINS=http://localhost:5173,http://localhost:3000
UPLOAD_MAX_SIZE=5242880
UPLOAD_ALLOWED_TYPES=image/jpeg,image/png,image/gif,image/webp
UPLOAD_DIR=uploads
此 PHP 開發技能為使用最新 PHP 版本建置安全、高效能 Web 應用程式提供了一個全面的架構。它強調現代 PHP 功能、安全編碼實務和結構良好的程式碼組織。按照此指南,開發人員可以建立可維護、可測試且可擴展的 PHP 應用程式,並遵循業界最佳實務。