使用Swoole可通过HTTP服务器结合路径解析与请求方法判断实现RESTful API,支持GET、POST、PUT、DELETE等操作,通过路由匹配处理用户资源的增删改查,并返回JSON响应,具备高性能优势。

1. 创建 Swoole HTTP 服务器
首先启动一个 Swoole HTTP 服务器,监听指定端口:
$http = new Swoole\Http\Server("0.0.0.0", 9501);
$http->on('start', function ($server) {
echo "HTTP Server is started at http://0.0.0.0:9501\n";
});
2. 实现简单的 RESTful 路由分发
在 request 回调中,根据请求的路径和方法进行分发:
$http->on('request', function ($request, $response) {
$path = parse_url($request->server['request_uri'], PHP_URL_PATH);
$method = $request->server['request_method'];
// 设置通用响应头
$response->header('Content-Type', 'application/json');
// 模拟用户资源路由
if ($path === '/api/users' && $method === 'GET') {
$response->end(json_encode([
'code' => 0,
'data' => [['id' => 1, 'name' => 'Alice'], ['id' => 2, 'name' => 'Bob']]
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'GET') {
$userId = $matches[1];
$response->end(json_encode([
'code' => 0,
'data' => ['id' => $userId, 'name' => 'User' . $userId]
]));
} elseif ($path === '/api/users' && $method === 'POST') {
$data = json_decode($request->rawContent(), true);
$response->status(201);
$response->end(json_encode([
'code' => 0,
'message' => 'User created',
'data' => $data
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'PUT') {
$userId = $matches[1];
$data = json_decode($request->rawContent(), true);
$response->end(json_encode([
'code' => 0,
'message' => "User {$userId} updated",
'data' => $data
]));
} elseif (preg_match('#^/api/users/(\d+)$#', $path, $matches) && $method === 'DELETE') {
$userId = $matches[1];
$response->end(json_encode([
'code' => 0,
'message' => "User {$userId} deleted"
]));
} else {
$response->status(404);
$response->end(json_encode(['code' => 404, 'message' => 'Not Found']));
}
});
3. 启动服务
添加最后的启动命令:
$http->start();
保存为 server.php,运行:php server.php
即可通过以下方式测试:
- GET /api/users → 获取用户列表
- GET /api/users/1 → 获取 ID 为 1 的用户
- POST /api/users → 创建用户(需带 JSON 数据)
- PUT /api/users/1 → 更新用户
- DELETE /api/users/1 → 删除用户
4. 可扩展优化建议
实际项目中可进一步优化:
- 引入路由类或正则路由表,统一管理路径与回调
- 封装 Request 和 Response 对象,提升开发体验
- 集成中间件机制(如鉴权、日志)
- 结合协程客户端实现异步数据获取
- 使用 Composer 加载依赖,结构更清晰










