详细信息 您现在的位置是:首页 > ThinkPHP
TP6路由要知道的内容
来源:
发布时间:2021-08-27
1092 人已围观
摘要Thinkphp的路由的主要作用是为了让URL地址更加美观、简洁、优雅;同事也会对我们站点优化提供一些好处。
路由功能是默认开启的config/app.php文件中设置:
'with_route' => true;
路由配置文件:config/route.php
路由定义文件:route/app.php
route目录下的定义文件的文件名是随机的,都会有效。
定义一次路由测试的文件:Address.php
class Address{
public function index() {
return 'index';
}
public function details($id) {
return 'details目前调用的ID'.$id;
}
}
未定义路由规则的情况下,默认的URL访问方法
http://xxx.com/Index.php/address/id/5
定义URL路由规则,在route/app.php定义文件中配置
Route::rule('details/:id','Address/details')
http://xxx.com/Index.php/details/5
路由规则配置完成后,必须使用路由规则进行访问;否则视为非法请求
注册路由定义
Route::rule('路由表达式','路由地址','请求类型')
路由表达式:泛指路由访问规则
路由地址:泛指访问目标的地址(控制器/方法/参数)
请求类型:默认 -> any
类型 | 描述 | 快捷方法 |
---|---|---|
GET | GET请求 | get |
POST | POST请求 | post |
PUT | PUT请求 | put |
DELETE | DELETE请求 | delete |
PATCH | PATCH请求 | patch |
* | 任何请求类型 | any |
快捷注册路由定义:
Route::[快捷方法名]('路由表达式','路由地址')
示例:
Route::rule('details/:id','Address/details')
URL:http://xxx.com/Index.php/details/5
注册rule路由到Address控制器的details
强制路由:设置开启了强制路由,所有访问都会要求按照路由访问规则进行,否则报错;
// 是否强制使用路由
'url_route_must' => true,
首页路由配置:(反斜杠就是首页地址)
Route::rule('/','Index/index');
路由规则表达式
规则表达式通常包含静态规则和动态规则,以及两种规则的结合,例如下面都属于有效的规则表达式:
// 静态路由 Route::rule('ads','Address/index'); [URL]=> tp/Index.php/ads // 静态+动态路由 Route::rule('datails/:id','Address/details'); [URL]=> tp/Index.php/details // (多参数)静态+动态路由 Route::rule('search/:id/:uid','Address/search'); [URL]=> tp/Index.php/search/1/1 // 全动态地址 不会限制search参数固定 Route::rule(':search/:id/:uid','Address/search'); [URL]=> tp/Index.php/search/1/1 [URL]=> tp/Index.php/s/1/1 // 可选参数地址 Route::rule('blog/:year/[:month]','Address/blog'); // 完全匹配地址 Route::rule('search/:id/:uid$','Address/search'); [URL]=> tp/Index.php/search/1/1 //在路由配置文件中可以开启全局路由完全匹配 //开启完全匹配后,使用`completeMatch(false)`关闭 // 额外参数 (隐式传值) // 路由跳转支持传入不显示在URL中参数 Route::rule('blog/:id','blog/read') ->append(['status'=>1,'app_id'=>5]); 路由标识 根据路由生成URL地址,定义路由的时候指定生成唯一性标识 // 定义标识 Route::rule('blog/:year/:month','Adderss/blog') ->name('route_blog'); return url('route_blog', ['year'=>$year,'month'=>$month] );
上一篇: Tp6的initialize函数不执行
下一篇: 数据分批处理chunk
站点信息
- 电话:15226178738
- QQ:1697915848
- 邮箱:1697915848@qq.com