WebMan 自动按照 HTTP METHOD 请求对应 Controller 方法
<?php
Route::any(
'/api{Endpoint:.*}',
function ($request, $endpoint) {
//转驼峰
$camelize = fn ($str) => str_replace(
' ',
'',
ucwords(
preg_replace(
"/([^a-zA-Z0-9])/",
" ",
ucfirst($str)
)
)
);
//请求的方法
$request_method = ucfirst(strtolower($request->method()));
//Endpoint列表
$endpoints = explode('/', $endpoint);
//驼峰转换类名
$class = 'app\api\controller\\' . $camelize($endpoints[1]);
//驼峰转换方法
$method = isset($endpoints[2]) ? $camelize($endpoints[2]) : false;
//判断类存在
if (class_exists($class)) {
$class = new $class();
//默认调用Index方法
if (!$method) {
$method = 'Index';
}
//拼接对应请求方法的类方法
$class_method = $method . $request_method;
//判断方法存在
if (method_exists($class, $class_method)) {
//优先选择对应请求方法的类方法执行
return call_user_func([$class, $class_method], $request);
} elseif (method_exists($class, $method)) {
//执行通用请求方法的类(驼峰结尾不带请求方法名称)
return call_user_func([$class, $method], $request);
}
}
//404
return json(['code' => 404, 'message' => 'Not Found'])->withStatus(404);
}
);
app\api\controller
下按照规范写对应请求的方法
标签:
订阅评论
登录
0 评论