美文网首页
thinkphp5 路由总结 从配置到模版页面访问

thinkphp5 路由总结 从配置到模版页面访问

作者: geeooooz | 来源:发表于2017-12-28 15:10 被阅读149次

    1.开启路由配置

    首先,我使用的是混合模式 关于模式请点击 https://www.kancloud.cn/manual/thinkphp5/118019

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

    // 按照顺序解析变量
    'url_param_type'    =>  1,
    
    'url_route_must' => true,//表示强制开启 必须定义路由才能访问 一般都是为false
    

    2.路由具体配置

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

    <?php
    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 出现以下场景 是正确的


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

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

    return [
            // 路由参数name为可选
            'hello/[:name]' => 'index/index/hello',
    

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

    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的,所以下面的访问地址:

    http://auth.com/hello// 无效
    http://auth.com/hello.html// 有效
    http://auth.com/hello/thinkphp// 无效
    http://auth.com/hello/thinkphp.html// 有效

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

    <?php
    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+']],
      ],
    ];
    

    关于更多的route下 路由配置可以去tp5官方文档查看https://www.kancloud.cn/manual/thinkphp5/118029
    也可以看看这篇文章 http://www.php.cn/php-weizijiaocheng-383385.html

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

    <a href="{:url('index/blog/get', 'id=1')}"><p>Go</p></a>
    

    index/blog/get 及 id=1 对应


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

    TP5里面是这么写的


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

    相关文章

      网友评论

          本文标题:thinkphp5 路由总结 从配置到模版页面访问

          本文链接:https://www.haomeiwen.com/subject/jqfvgxtx.html