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

首先启动一个 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";
});
在 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']));
}
});
添加最后的启动命令:
$http->start();
保存为 server.php,运行:php server.php
即可通过以下方式测试:
实际项目中可进一步优化:
以上就是Swoole怎么实现一个支持RESTful风格的API服务的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号