Blogger Information
Blog 40
fans 1
comment 0
visits 32431
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
tp框架配置路由的初学习
李明伟的博客
Original
1768 people have browsed it

路由定义在route目录下的route.php中。

最普通的路由——

路由到模块\控制器\方法

//路由到模块/控制器/操作
Route::rule('demo1','index/test/demo1')//rule方法将原有的地址路径映射到rule中,此时原本的路径失效
        ->method('get');//method用于设置请求方法

路由到一个闭包函数的写法

//路由到一个闭包函数
Route::rule('demo2',function (){
    return 'tp框架';
})->method('get');//可以使用rule方法将一个闭包函数映射到rule上

如何开启强制路由

QQ浏览器截图20190401194944.png

当开启强制路由时,就必须定义首页的路由规则,之后所有的路径都需要定义路由规则

//若开启了强制路由,首页也要定义路由规则
Route::rule('/','index/index/index')
        ->method('get');

当控制器中涉及变量参数时,则需要使用路由变量

其中涉及了对url的参数的解析方式的配置QQ浏览器截图20190401195630.png

在配置路由时参数的写法——在rule中填写参数时需要在变量名前加’:‘,添加方括号代表该变量为可选变量

路由变量
Route::rule('route1/:name/[:course]/[:grade]','index/test/route1')
        ->method('get');//在rule中填写参数时需要在变量名前加:,添加方括号代表该变量为可选变量

在路由中可以自定义路由表达式的分隔符

//自定义路由表达式的分隔符
Route::rule('route1-:name-[:course]-[:grade]','index/test/route1')
     ->method('get');//用'-'代替'/'

对路由变量中的变量进行约束与验证

使用框架中Route类提供的pattern方法实现对路由变量的约束与验证(支持数组形式)

//对路由变量中的变量进行约束与验证
Route::rule('route1-<name>-<course?>-<grade?>','index/test/route1')
    ->method('get')
    ->pattern(['name'=>'[a-zA-Z]+','course'=>'[a-zA-z]+','grade'=>'[0-9]+']);//'/d'可代替[0-9']
    //pattern方法可对路由变量进行约束与验证

路由参数

常用的几个参数——ext:URL后缀检测,支持匹配多个后缀,匹配多个后缀时需要使用"|"隔开

method——请求类型检测,支持多个请求类型

ajax——Ajax检测

更多的路由参数详见tp5.1的手册

代码示例

//路由参数
Route::rule('route2','index/test/route2')
    ->method('get')
    ->ext('html|shtml|png');//URL后缀检测,exc方法支持同时设置多个后缀,使用'|'隔开,也可使用链式调用,设置为空后表示不允许添加URL后缀

URL生成

使用URL类中的build方法

控制器中的方法

//URL生成
public function route3(){
    $url = Url::build('index/test/route1',['name'=>'zhu','course'=>'java','grade'=>'98']);
    $url = Url::build('index/route1/zhu/java/98');//URL的build方法也可以构造路由地址
    dump($url);
}

路由配置的部分

QQ浏览器截图20190401202042.png

注:若使用想省去tp框架中index模块的php后缀许要进行以下操作

找到public目录下的static目录下的apache配置文件

QQ浏览器截图20190401202625.png

在index.php后添加'?'

QQ浏览器截图20190401202802.png


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!