推薦目錄??
/my-rest-api/
├── api/v1/index.php # 唯一入口
├── data/users.json # 臨時“數據庫”
└── .htaccess # 路由重寫
.htaccess 一鍵把所有請求塞進入口:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^api/v1/(.*)$ api/v1/index.php?request=$1 [QSA,L]
寫完先讓「代碼審查助手」掃一遍,確保正則沒寫爆,安全分 +1 ??!
以下代碼已修復原文 > 亂碼,直接粘進 index.php 就能跑 ?
<?php
header("Content-Type: application/json; charset=utf-8");
/*========== 工具函數 ==========*/
function getUsers(): array {
return json_decode(file_get_contents(__DIR__.'/../../data/users.json'), true) ?: [];
}
function saveUsers(array $users): void {
file_put_contents(__DIR__.'/../../data/users.json', json_encode($users, JSON_PRETTY_PRINT));
}
/*========== 路由分發 ==========*/
$method = $_SERVER['REQUEST_METHOD'];
$endpoint = trim($_GET['request'] ?? '', '/');
switch ($method) {
case 'GET': handleGet($endpoint); break;
case 'POST': handlePost(); break;
case 'PUT': handlePut($endpoint); break;
case 'DELETE': handleDelete($endpoint); break;
default:
http_response_code(405);
echo json_encode(['message' => 'Method Not Allowed']);
}
/*========== CRUD 處理器 ==========*/
function handleGet(string $req): void
{
$users = getUsers();
if ($req === '') {
echo json_encode($users);
return;
}
$user = array_filter($users, fn($u) => $u['id'] == $req);
$user ? echo json_encode(array_values($user)[0])
: echo json_encode(['message' => 'User not found'], JSON_PRETTY_PRINT);
}
function handlePost(): void
{
$input = json_decode(file_get_contents('php://input'), true);
$users = getUsers();
$newId = $users ? end($users)['id'] + 1 : 1;
$newUser = ['id' => $newId, 'name' => $input['name'], 'email' => $input['email']];
$users[] = $newUser;
saveUsers($users);
http_response_code(201);
echo json_encode($newUser, JSON_PRETTY_PRINT);
}
function handlePut(string $req): void
{
$input = json_decode(file_get_contents('php://input'), true);
$users = getUsers();
foreach ($users as &$u) {
if ($u['id'] == $req) {
$u['name'] = $input['name'];
$u['email'] = $input['email'];
saveUsers($users);
echo json_encode($u, JSON_PRETTY_PRINT);
return;
}
}
echo json_encode(['message' => 'User not found'], JSON_PRETTY_PRINT);
}
function handleDelete(string $req): void
{
$users = getUsers();
foreach ($users as $k => $u) {
if ($u['id'] == $req) {
array_splice($users, $k, 1);
saveUsers($users);
echo json_encode(['message' => 'User deleted'], JSON_PRETTY_PRINT);
return;
}
}
echo json_encode(['message' => 'User not found'], JSON_PRETTY_PRINT);
}
想再懶一點?「代碼生成」30 秒給你生成完整 CRUD 模板,接著「代碼優化」自動把 N+1 查詢、重復連接池全部修好,性能翻倍 ??!
# 查全部
curl http://localhost/api/v1/
# 查單用戶
curl http://localhost/api/v1/1
# 新增
curl -X POST http://localhost/api/v1/ \
-H "Content-Type: application/json" \
-d '{"name":"Alice","email":"alice@ok.com"}'
# 更新
curl -X PUT http://localhost/api/v1/1 \
-H "Content-Type: application/json" \
-d '{"name":"Alice Pro","email":"alice@pro.com"}'
# 刪除
curl -X DELETE http://localhost/api/v1/1
測試通過后用「代碼文檔生成器」一鍵生成 Markdown 接口文檔,前端同事直呼友好 ??!
filter_var($email, FILTER_VALIDATE_EMAIL) 走一波 ?? users.json 換成 MySQL,再用 PDO 預編譯語句,SQL 注入說拜拜 ?? 把上述檢查點寫進「開發任務管理系統KPI」——“高危漏洞修復時長 ≤ 1 個工作日”,目標量化,安全不背鍋 ??!
原生 PHP 也能寫出優雅、易維護的 RESTful API:
目錄清晰 → 路由重寫 → CRUD 封裝 → 文檔自動生成,全程 AI 提示詞護航,開發效率直接 ×2 ??!
原文鏈接: https://200oksolutions.com/blog/lightweight-php-restful-api/