使用 SplServer 和 SplRoute 实现 RESTful API,核心是解析 URI 路径与 HTTP Method,通过路由表分发到对应处理函数。

RESTful 路由原理与结构
RESTful 的核心在于用 HTTP Method 区分操作:GET 查询、POST 创建、PUT 更新、DELETE 删除。PHP 原生实现需从 $_SERVER['REQUEST_URI'] 提取路径,并匹配预设的路由规则。

路由表通常以数组形式存储,键为路径模式(如 /api/users),值为对应的回调函数或类方法。匹配时需考虑参数占位符(如 /api/users/:id)。服务器根据请求的 Method 选择执行哪个回调,未匹配则返回 404。
完整路由分发程序
将以下代码保存为 index.php,在 PHP 内置服务器运行:php -S localhost:8000 index.php。访问不同路径观察输出。

<?php
// 简单 RESTful API 路由示例
// 1. 定义路由表
$routes = [
'GET /api/users' => 'getUsers',
'POST /api/users' => 'createUser',
'GET /api/users/:id' => 'getUserById',
'PUT /api/users/:id' => 'updateUser',
'DELETE /api/users/:id' => 'deleteUser'
];
// 2. 模拟数据存储
$users = [
['id' => 1, 'name' => 'Alice'],
['id' => 2, 'name' => 'Bob']
];
// 3. 获取请求信息
$method = $_SERVER['REQUEST_METHOD'];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// 4. 路由匹配
$matchedRoute = null;
$params = [];
foreach ($routes as $routePattern => $handler) {
list($routeMethod, $routePath) = explode(' ', $routePattern);
if ($routeMethod !== $method) continue;
// 简单参数提取:/api/users/:id -> id=123
$patternParts = explode('/', trim($routePath, '/'));
$uriParts = explode('/', trim($requestUri, '/'));
if (count($patternParts) !== count($uriParts)) continue;
$isMatch = true;
foreach ($patternParts as $index => $part) {
if (strpos($part, ':') === 0) {
$params[substr($part, 1)] = $uriParts[$index];
} elseif ($part !== $uriParts[$index]) {
$isMatch = false;
break;
}
}
if ($isMatch) {
$matchedRoute = $handler;
break;
}
}
// 5. 执行处理或返回 404
if (!$matchedRoute) {
http_response_code(404);
echo json_encode(['error' => 'Not Found']);
exit;
}
// 6. 调用处理函数
try {
$result = $matchedRoute($params);
header('Content-Type: application/json');
echo json_encode($result);
} catch (Exception $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
// 7. 具体业务逻辑函数
function getUsers($params) {
return ['data' => $GLOBALS['users']];
}
function createUser($params) {
$input = json_decode(file_get_contents('php://input'), true);
if (!$input || !isset($input['name'])) {
throw new Exception('Invalid input');
}
$newUser = ['id' => count($GLOBALS['users']) + 1, 'name' => $input['name']];
$GLOBALS['users'][] = $newUser;
return ['data' => $newUser, 'message' => 'Created'];
}
function getUserById($params) {
$id = $params['id'];
$user = array_values(array_filter($GLOBALS['users'], fn($u) => $u['id'] == $id))[0] ?? null;
if (!$user) throw new Exception('User not found');
return ['data' => $user];
}
function updateUser($params) {
$id = $params['id'];
$input = json_decode(file_get_contents('php://input'), true);
if (!$input) throw new Exception('Invalid input');
foreach ($GLOBALS['users'] as &$user) {
if ($user['id'] == $id) {
$user['name'] = $input['name'] ?? $user['name'];
return ['data' => $user, 'message' => 'Updated'];
}
}
throw new Exception('User not found');
}
function deleteUser($params) {
$id = $params['id'];
foreach ($GLOBALS['users'] as $key => $user) {
if ($user['id'] == $id) {
unset($GLOBALS['users'][$key]);
return ['message' => 'Deleted'];
}
}
throw new Exception('User not found');
}
运行后,发送 GET /api/users 返回所有用户列表;POST /api/users 发送 JSON {"name":"Charlie"} 返回新创建的用户对象;GET /api/users/1 返回 ID 为 1 的用户详情。若路径不匹配或 Method 错误,返回 404 JSON 错误。注意 POST/PUT 需设置 Header Content-Type: application/json 且 Body 为合法 JSON 字符串。
该程序演示了基础的路由注册与分发逻辑,支持简单的路径参数提取。
处理 JSON 输入与响应头
POST 和 PUT 请求的数据不在 $_POST 中,需读取 php://input 并解码 JSON。
必须设置正确的 Content-Type 响应头(如 application/json),否则前端可能无法正确解析。同时需处理非法 JSON 导致的解码错误,避免程序崩溃。