TP5 路由设置
TP5路由注册
按照TP5官方文档Restful资源路由可以这样简化编写:
Route::get('api/:ver/test', 'api/:ver.test/index');
Route::get('api/:ver/test/:number', 'api/:ver.test/read');
表示我们通过下面这两个url:
http://www.abc.com/api/v1/test
http://www.abc.com/api/v1/test/123
可以分别访问控制器index和read这两个方法。但是经过实验,这两个url只会访问index方法。
这不科学,继续研究,我通过另一种方法注册路由:
Route::resource('api/:ver/test', 'api/:ver.test');
自动生成7个路由规则,如下:
标识 | 请求类型 | 生成路由规则 | 对应操作方法(默认) |
---|---|---|---|
index | GET | blog | index |
create | GET | blog/create | create |
save | POST | blog | save |
read | GET | blog/:id | read |
edit | GET | blog/:id/edit | edit |
update | PUT | blog/:id | update |
delete | DELETE | blog/:id | delete |
然而这次可以正确的通过不同url访问不同的控制器方法,Why?
先看看Route::resource
方式是怎么注册路由的。
定位到Route.php文件resource方法:
public static function resource($rule, $route = '', $option = [], $pattern = [])
{
if (is_array($rule)) {
foreach ($rule as $key => $val) {
if (is_array($val)) {
list($val, $option, $pattern) = array_pad($val, 3, []);
}
self::resource($key, $val, $option, $pattern);
}
} else {
if (strpos($rule, '.')) {
// 注册嵌套资源路由
$array = explode('.', $rule);
$last = array_pop($array);
$item = [];
foreach ($array as $val) {
$item[] = $val . '/:' . (isset($option['var'][$val]) ? $option['var'][$val] : $val . '_id');
}
$rule = implode('/', $item) . '/' . $last;
}
// 注册资源路由
foreach (self::$rest as $key => $val) {
if ((isset($option['only']) && !in_array($key, $option['only']))
|| (isset($option['except']) && in_array($key, $option['except']))) {
continue;
}
if (isset($last) && strpos($val[1], ':id') && isset($option['var'][$last])) {
$val[1] = str_replace(':id', ':' . $option['var'][$last], $val[1]);
} elseif (strpos($val[1], ':id') && isset($option['var'][$rule])) {
$val[1] = str_replace(':id', ':' . $option['var'][$rule], $val[1]);
}
$item = ltrim($rule . $val[1], '/');
$option['rest'] = $key;
self::rule($item . '$', $route . '/' . $val[2], $val[0], $option, $pattern);
}
}
}
查看最后一行代码发现resource方法内部给路由规则后面加了个$
符号。
修改
Route::get('api/:ver/test$', 'api/:ver.test/index');
Route::get('api/:ver/test/:number$', 'api/:ver.test/read');
发现一切正常了,两个方法可以正常访问到。
但是在文档没有看到使用$
的说明,所以继续找正确的方法,最后在setRule方法发现了端倪:
complete_match这个选项表示是否完整匹配路由,然后我查看了项目的配置文件:
// 路由使用完整匹配
'route_complete_match' => false,
项目配置并没有使用路由完整性匹配,所以只要找到了第一个匹配的路由就会进入该方法,而resouce方法使用神奇的内部符号$
,相当于针对该路由设置了完整性匹配规则。所以正确的使用办法应该是:
修改'route_complete_match' => true,
或者给路由添加['complete_match' => true]
选项
Route::get('api/:ver/test$', 'api/:ver.test/index', ['complete_match' => true]);
Route::get('api/:ver/test/:number$', 'api/:ver.test/read', ['complete_match' => true]);
一切正常~
未完待续~~~