ThinkPHP5路由
1 PathInfo方式的路由
平常我们按照习惯去访问我们的ThinkPHP项目的时候,常规的url应该是这样子写的,(本地举例)http://localhost/项目名/public/index.php/模块名/控制器名/方法名
本地项目结构,Apache/htdocs/项目名/application/模块名/controller/控制器名(包含方法)
Apache/htdocs/项目名 /public/index.php
可以看出public/index.php为入口文件。后面路径按照模块控制器方法排序即可。显然这种方式即复杂,安全性又差,所以才有了Route访问方式。
2 Route方式的路由
打开application/config.php

确保开启了,建议把强制使用路由改为true,使用中记得改成true后无法再用PathInfo方式访问。
打开application/route.php

注释掉已有代码添加
use think\Route;
Route::rule('demo','index/hello/hello','GET');
//index为模块名,第一个hello为控制器名,第二个为方法名
至此可直接在浏览器http://localhost/项目名/public/index.php/demo 访问之前的PathInfo
路径
也可简写
Route::get('demo','index/hello/hello');
如果想将路径中 localhost/项目名/public/index.php部分,换成自己域名,在Apache虚拟环境要更改apache\conf\extra\httpd-vhosts.conf文件。
<VirtualHost *:80>
##ServerAdmin webmaster@dummy-host2.example.com
DocumentRoot "C:\xampp\htdocs\项目名\public"
ServerName 域名
##ErrorLog "logs/dummy-host2.example.com-error.log"
##CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>
这样就可以通过http://域名/demo访问。
3 Route路由的参数传递
(1) 控制器方法参数传递
目录application\index\controller\hello.php
<?php
namespace app\index\controller;
class Hello
{
public function hello($id,$name,$job)
{
return $id.'|'.$name.'|'.$job;
}
}
对应Route路由
Route::rule('demo/:id','index/hello/hello','GET');
第一个参数,:id,:自定义的变量。如,Route::get('hello/:id', 'sample/Test/hello');
第二个参数,URL路径中,?参数名=参数值。
第三个参数,与第二个参数用&连接
注意事项:控制器方法参数名要与url传进来参数名一致。
上例子为get请求带的参数。试着使用post方式把job参数放到body里。
只需更改Route路由,我们使用另一种写法。
Route::post('demo/:id', 'index/hello/hello');
在postman form-data中key为job,value为j
url为http://域名/demo/1?name=m
返回结果和上次一致。
(2) Request方法来获取参数
先要引入Request类,再通过Request::instance()->param('id')方法
<?php
namespace app\index\controller;
use think\Request;
class Hello
{
public function hello()
{
$id =Request::instance()->param('id');
$name =Request::instance()->param('name');
$job =Request::instance()->param('job');
$all=Request::instance()->param();//获取所有参数,数组$all['id']
return $id.'|'.$name.'|'.$job;
}
}
注意:其中Request也可以通过依赖注入的方式,作为hello(Resquest request->param('id').
(3)助手函数input()
<?php
namespace app\index\controller;
use think\Request;
class Hello
{
public function hello()
{
$id =input('id'); //不加get或post等
$name =input('get.name');
$job =input('get.job'); //post方式用post.job
$all=input(('param.')//获取所有参数,数组
return $id.'|'.$name.'|'.$job;
}
}
三种方法,个人更倾向与第二种,简单明了
网友评论