thinkphp-路由

47次阅读

共计 8723 个字符,预计需要花费 22 分钟才能阅读完成。

路由定义文件

route 定义下的所有的路由文件都是有效的

定义路由必须使用

use think\facade\Route;

控制器定义

<?php
namespace app\admin\controller;
class Index
{public function Index($number){echo $number;}

}

修改配置文件,强制路由访问

此时已经开启多应用配置

目录文件如下

修改配置文件,启用路由

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [WE CAN DO IT JUST THINK]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (http://www.apache.org/licenses/LICENSE-2.0)
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------

use think\facade\Env;

return [
    // 应用地址
    'app_host'         => Env::get('app.host', ''),
    // 应用 Trace(环境变量优先读取)'app_trace'        => false,
    // 应用的命名空间
    'app_namespace'    => '',
    // 是否启用路由
    'with_route'       => true,
    // 是否启用事件
    'with_event'       => true,
    // 自动多应用模式
    'auto_multi_app'   => true,
    // 应用映射(自动多应用模式有效)'app_map'          => [],
    // 域名绑定(自动多应用模式有效)'domain_bind'      => [],
    // 禁止 URL 访问的应用列表(自动多应用模式有效)'deny_app_list'    => [],
    // 默认应用
    'default_app'      => 'index',
    // 默认时区
    'default_timezone' => 'Asia/Shanghai',
    // 默认验证器
    'default_validate' => '',

    // 异常页面的模板文件
    'exception_tmpl'   => app()->getThinkPath() . 'tpl/think_exception.tpl',

    // 错误显示信息, 非调试模式有效
    'error_message'    => '页面错误!请稍后再试~',
    // 显示错误信息
    'show_error_msg'   => true,
];

再次修改配置文件,强制路由

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [WE CAN DO IT JUST THINK]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (http://www.apache.org/licenses/LICENSE-2.0)
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------

return [
    // PATHINFO 变量名 用于兼容模式
    'var_pathinfo'          => 's',
    // 兼容 PATH_INFO 获取
    'pathinfo_fetch'        => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    // pathinfo 分隔符
    'pathinfo_depr'         => '/',
    // HTTPS 代理标识
    'https_agent_name'      => '',
    // URL 伪静态后缀
    'url_html_suffix'       => 'html',
    // URL 普通方式参数 用于自动生成
    'url_common_param'      => true,
    // 是否开启路由延迟解析
    'url_lazy_route'        => false,
    // 是否强制使用路由
    'url_route_must'        => true,
    // 合并路由规则
    'route_rule_merge'      => false,
    // 路由是否完全匹配
    'route_complete_match'  => false,
    // 使用注解路由
    'route_annotation'      => false,
    // 是否开启路由缓存
    'route_check_cache'     => false,
    // 路由缓存连接参数
    'route_cache_option'    => [],
    // 路由缓存 Key
    'route_check_cache_key' => '',
    // 访问控制器层名称
    'controller_layer'      => 'controller',
    // 空控制器名
    'empty_controller'      => 'Error',
    // 是否使用控制器后缀
    'controller_suffix'     => false,
    // 默认的路由变量规则
    'default_route_pattern' => '[\w\.]+',
    // 域名根,如 thinkphp.cn
    'url_domain_root'       => '',
    // 是否自动转换 URL 中的控制器和操作名
    'url_convert'           => true,
    // 表单请求类型伪装变量
    'var_method'            => '_method',
    // 表单 ajax 伪装变量
    'var_ajax'              => '_ajax',
    // 表单 pjax 伪装变量
    'var_pjax'              => '_pjax',
    // 是否开启请求缓存 true 自动缓存 支持设置请求缓存规则
    'request_cache'         => false,
    // 请求缓存有效期
    'request_cache_expire'  => null,
    // 全局请求缓存排除规则
    'request_cache_except'  => [],
    // 默认控制器名
    'default_controller'    => 'Index',
    // 默认操作名
    'default_action'        => 'index',
    // 操作方法后缀
    'action_suffix'         => '',
    // 默认 JSONP 格式返回的处理方法
    'default_jsonp_handler' => 'jsonpReturn',
    // 默认 JSONP 处理方法
    'var_jsonp_handler'     => 'callback',
];

再次定义 admin 下的路由

<?php
use think\facade\Route;

// 当访问 ming/34 的时候 路由到 index 控制器下的 index 方法,并传入参数 numer=34
Route::rule('ming/:number', 'index/index');

此时访问 http://localhost:8082/admin/ming/34

已经开始路由

正常访问

没有路由

此时开启强制路由以后,首页需要开启路由

由于默认的应用为 index 所以需要在 route 定义 index

目录如下

定义首页目录

<?php

use think\facade\Route;

Route::rule('/', 'index/index');

此时访问首页
http://localhost:8082/
会被重定向到 index 控制器下的 index 方法

变量规则

变量规则,这里定义的是

Route::get('new/:name', 'News/read')
    ->pattern(['name' => '[\w|\-]+']);

此时匹配的是 name 变量的匹配的规则,匹配的规则是双斜杠

路由规则

// 定义动态路由
Route::get('hello/:name', 'index/:name/hello');

可以做到把一个变量传入另外一个路由中

路由地址

路由到控制器的操作
添加一个控制器

此控制器使用 appadmincontroller 命名空间 其文件内容如下

<?php


namespace app\admin\controller;


class Blog
{public function read($id){return $id;}
}

传入 $id 作为参数

再次定义路由规则如下

Route::get('blog/:id', 'Blog/read');

此时访问 admin 模块下的 blog 内容,会匹配:id 的内容,
http://localhost:8082/admin/blog/23/ 此时会匹配 23 内容

其结果如下

路由地址

路由到控制器操作

路由到控制器和操作

上面的例子就是

路由到类的方法

这种方式可以执行任何方法

Route::get('blog/:id','\app\index\service\Blog@read');
Route::get('blog/:id','\app\index\service\Blog::read');

上方执行的是 Blog 的 read 方法或者 read 的静态方法

重定向路由

Route::redirect('blog/:id', 'http://blog.thinkphp.cn/read/:id', 302);

使用 302 重定向一个新的地址

路由到模板

使用路由到模板直接渲染

<?php
use think\facade\Route;

Route::view('blog', 'hello');

访问 http://localhost:8082/admin/blog/ 此时会渲染出

闭包支持

使用闭包可以使用一些特殊需求的路由,不需要再次执行控制器的操作了

<?php
use think\facade\Route;

Route::get('blog/:name', function ($name){return $name;});

http://localhost:8082/admin/blog/34

闭包中可以实现依赖注入

<?php
use think\facade\Route;

Route::rule('blog/:name', function (\think\Request $request, $name){$method = $request->method();
    return $method . $name;
});

此时由于依赖 request 会自动注入 request

路由参数

对当前的路由进行匹配。。

<?php
use think\facade\Route;

Route::rule('blog/:id', 'blog/read')
    ->ext('html')   // url 后缀检测
    ->https();  // https 检测

只有全部符合要求才能匹配到

额外追加参数

使用 append 额外追加参数

<?php
use think\facade\Route;

Route::rule('blog/:id', 'blog/read')
->append(['app_id' => 1, 'status' => 1]
);

此时会传入两个参数 app_id 和 status 两个参数

绑定模型

支持绑定模型

Route::get('hello/:id', 'index/hello')
    ->model('\app\index\model\User');

支持从模型层中直接获取数据

同时可以使用闭包,获取数据

Route::rule('hello/:id', 'index/hello')
    ->model(function ($id) {
        $model = new \app\index\model\User;
        return $model->where('id', $id)->find();});

请求缓存

Route::get('new/:name$', 'News/read')
    ->cache(3600);

表示直接请求 3600 秒

路由中间件

可以在路由中,数据直接传给中间件

路由分组

可以对公有的路由进行分组操作

<?php
use think\facade\Route;

Route::group('blog', function (){Route::rule(':id', 'blog/read');
    Route::rule(':name', 'blog/read');
})->ext('html')->pattern([
    'id' => '\d+',
    'name' => '\w+'
]);

此时,可以根据正则匹配路由

资源路由

<?php


namespace app\admin\controller;


class Blog
{public function index(){ }

    public function read($id){return $id . "read";}

    public function edit($id){return $id . "edit";}
}
<?php
use think\facade\Route;

Route::resource('blog', 'Blog');

此时访问
http://localhost:8082/admin/blog/34/edit 会调用 edit 方法
http://localhost:8082/admin/blog/34/read 会调用 read 方法

资源嵌套

路由支持资源嵌套

注解路由

修改配置文件,实现注解路由

<?php
// +----------------------------------------------------------------------
// | ThinkPHP [WE CAN DO IT JUST THINK]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed (http://www.apache.org/licenses/LICENSE-2.0)
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 应用设置
// +----------------------------------------------------------------------

return [
    // PATHINFO 变量名 用于兼容模式
    'var_pathinfo'          => 's',
    // 兼容 PATH_INFO 获取
    'pathinfo_fetch'        => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    // pathinfo 分隔符
    'pathinfo_depr'         => '/',
    // HTTPS 代理标识
    'https_agent_name'      => '',
    // URL 伪静态后缀
    'url_html_suffix'       => 'html',
    // URL 普通方式参数 用于自动生成
    'url_common_param'      => true,
    // 是否开启路由延迟解析
    'url_lazy_route'        => false,
    // 是否强制使用路由
    'url_route_must'        => true,
    // 合并路由规则
    'route_rule_merge'      => false,
    // 路由是否完全匹配
    'route_complete_match'  => false,
    // 使用注解路由
    'route_annotation'      => true,
    // 是否开启路由缓存
    'route_check_cache'     => false,
    // 路由缓存连接参数
    'route_cache_option'    => [],
    // 路由缓存 Key
    'route_check_cache_key' => '',
    // 访问控制器层名称
    'controller_layer'      => 'controller',
    // 空控制器名
    'empty_controller'      => 'Error',
    // 是否使用控制器后缀
    'controller_suffix'     => false,
    // 默认的路由变量规则
    'default_route_pattern' => '[\w\.]+',
    // 域名根,如 thinkphp.cn
    'url_domain_root'       => '',
    // 是否自动转换 URL 中的控制器和操作名
    'url_convert'           => true,
    // 表单请求类型伪装变量
    'var_method'            => '_method',
    // 表单 ajax 伪装变量
    'var_ajax'              => '_ajax',
    // 表单 pjax 伪装变量
    'var_pjax'              => '_pjax',
    // 是否开启请求缓存 true 自动缓存 支持设置请求缓存规则
    'request_cache'         => false,
    // 请求缓存有效期
    'request_cache_expire'  => null,
    // 全局请求缓存排除规则
    'request_cache_except'  => [],
    // 默认控制器名
    'default_controller'    => 'Index',
    // 默认操作名
    'default_action'        => 'index',
    // 操作方法后缀
    'action_suffix'         => '',
    // 默认 JSONP 格式返回的处理方法
    'default_jsonp_handler' => 'jsonpReturn',
    // 默认 JSONP 处理方法
    'var_jsonp_handler'     => 'callback',
];

添加注解,实现路由

<?php
namespace app\controller;

/**
 * @route('blog')
 */
class Blog
{public function index()
    { }

    public function read($id)
    { }

    public function edit($id)
    {}}

路由绑定

支持绑定到控制器操作,命名空间,和类

// 绑定当前的 URL 到 Blog 控制器
Route::bind('blog');
// 绑定当前的 URL 到 Blog 控制器的 read 操作
Route::bind('blog/read');

原先访问 http://serverName/blog/read/id/5
需要访问 http://serverName/read/id/5 可以访问到

剩下的还可以绑定到命名空间 类

域名路由

使用 Route::domain 绑定子域

路由缓存

MISS 路由

MISS 路由为全局最后一条执行的路由

跨域请求

通过 allowCrossDomain 进行跨域请求

URL 请求

用于生成 url 请求
路由规则

<?php
use think\facade\Route;

Route::rule('blog/:id', 'blog/read');
<?php


namespace app\admin\controller;


class Blog
{public function index(){ }

    public function read($id){var_dump(url('index/blog/read', ['id' => 5, 'name' => 'ming']));
        return $id;
    }
}

正文完
 0