您的当前位置:首页>全部文章>文章详情

【Webman+MySQL教程二】路由与控制器:参数获取、响应返回、路由分组

果子发表于:2026-10-04 13:34:22浏览:1次TAG: #webman #PHP #MySql #教程

本篇目标

理解 Webman 的路由分发机制,掌握控制器编写、请求参数获取、响应返回与路由分组。这是第 3 篇连接 MySQL 前的地基。

一、路由基础

路由文件在 config/route.php。最简单的三种写法:

use support\\Router;
use app\\controller\\StudentController;

// 1. 闭包(demo 可用,正式项目不推荐,不利于结构清晰)
Route::add('/ping', function () {
    return 'pong';
});

// 2. 指定请求方法
Route::get('/student/list', [StudentController::class, 'list']);
Route::post('/student/add', [StudentController::class, 'add']);

// 3. 通配所有方法
Route::add('/student/update', [StudentController::class, 'update']);

注意:Webman 默认自带兜底路由,即 /app/controller 下类名与文件名一致的路径可直接访问(例如 /student/list 会自动命中 app\controller\StudentController::list)。但显式注册路由更可控,推荐始终写 route.php。

二、动态路由与参数

// 通配符
Route::get('/student/{id}', [StudentController::class, 'detail']);

在控制器里通过 Request 取参数:

public function detail(Request $request, string $id)
{
    return json(['id' => $id]);
}

三、获取请求参数

Webman 的 support\Request 常用方法:

$request->get('page', 1);        // GET 参数,第二个参数是默认值
$request->post('name');          // POST body(form 表单)
$request->input('keyword');      // 先 GET 后 POST,都能取到
$request->all();                 // 所有参数
$request->file('avatar');        // 上传文件
$request->header('Authorization');
$request->method();              // 请求方法
$request->remoteIp();            // 客户端 IP

接收 JSON 请求体时,post() 默认解析不到。Webman 中可以用 $request->rawBody() 拿到原始字符串再 json_decode,或设置 support\Request 解析;最省心的做法是前端用 form/查询参数提交。

四、返回响应

// 字符串
return 'ok';

// JSON:全局 helper
return json(['code' => 0, 'data' => []]);
return json(['code' => 404], 404); // 可指定 HTTP 状态码

// 完整 Response
return response('hello')
    ->withHeader('X-Powered-By', 'webman');

// 重定向
return redirect('/student/list');

五、路由分组

接口变多后用分组统一管理,还可以按分组挂中间件(第 5 篇实战时会用到):

Route::group('/api', function () {
    Route::get('/student/list', [StudentController::class, 'list']);
    Route::post('/student/add', [StudentController::class, 'add']);
});

访问路径变为 /api/student/list。

六、小练习

创建一个 BookController,实现 GET /api/book/{id} 返回书名 JSON,并用浏览器直接改 URL 验证。做完即可进入第 3 篇。

小结

本篇过完了路由注册、参数获取、响应返回和分组。下一篇文章将安装 webman/database,配置 MySQL 连接池并处理中文乱码与时区问题。