php+路由配置如何访问地址吗,thinkphp5 路由总结 从配置到模版页面访问

1.开启路由配置

'url_route_on' => true, //开启路由

// 按照顺序解析变量

'url_param_type' => 1,

'url_route_must' => true,//表示强制开启 必须定义路由才能访问 一般都是为false

2.路由具体配置

首先,这是 index模块儿/Index控制器/hello方法

namespace app\index\controller;

use think\Controller;

class Index extends Controller

{

public function hello($name = 'World')

{

return 'Hello,' . $name . '!';

}

}

那么我们在application\route.php 中写入路由配置:

1.:name为传递的参数 必传 否侧报错

return [

// 添加路由规则 路由到 index控制器的hello操作方法

'hello/:name' => 'index/index/hello',

现在我们访问http://auth.com/hello/world 出现以下场景 是正确的

f4415c204229

那么我们访问 http://auth.com/hello/呢? 报错

f4415c204229

2.:name为选填参数 不是必传 []代表不是必传

return [

// 路由参数name为可选

'hello/[:name]' => 'index/index/hello',

现在再访问http://auth.com/hello 成功

f4415c204229

3.【完整匹配】

// 路由参数name为可选

'hello/[:name]$' => 'index/hello',

// 当路由规则以$结尾的时候就表示当前路由规则需要完整匹配。

// 当我们访问下面的URL地址的时候:

// http://auth.com/hello // 正确匹配

// http://auth.com/hello/thinkphp // 正确匹配

// http://auth.com/hello/thinkphp/val/value // 不会匹配

4.【路由参数】

return [

// 定义路由的请求类型和后缀

'hello/[:name]' => ['index/hello', ['method' => 'get', 'ext' => 'html']],

];

上面定义的路由规则限制了必须是get请求,而且后缀必须是html的,所以下面的访问地址:

现在重新在index模块下创建Blog控制器:

namespace app\index\controller;

class Blog

{

public function get($id)

{

return '查看id=' . $id . '的内容';

}

public function read($name)

{

return '查看name=' . $name . '的内容';

}

public function archive($year, $month)

{

return '查看' . $year . '/' . $month . '的归档内容';

}

}

现在就用到路由分组了

//【路由分组】

return [

'[blog]' => [

':year/:month' => ['index/blog/archive', ['method' => 'get'], ['year' => '\d{4}', 'month' => '\d{2}']],

':id' => ['index/blog/get', ['method' => 'get'], ['id' => '\d+']],

':name' => ['index/blog/read', ['method' => 'get'], ['name' => '\w+']],

],

];

3.如何在模版文件中跳转正确的路由

Go

index/blog/get 及 id=1 对应

f4415c204229

大致就是如此 其他的也都差不多

TP5里面是这么写的

f4415c204229

到这里就大功告成了 大家可以根据需求进行详细配置

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值