thinkphp 路由

路由定義文件

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

定義路由必須使用

use think\facade\Route;
2019-05-25-16-20-53----

控制器定義

<?php
namespace app\admin\controller;
class Index
{

    public function Index($number){
        echo $number;
    }

}

修改配置文件,強(qiáng)制路由訪問

此時(shí)已經(jīng)開啟多應(yīng)用配置

目錄文件如下

2019-05-25-16-47-10----

修改配置文件,啟用路由

<?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>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 應(yīng)用設(shè)置
// +----------------------------------------------------------------------

use think\facade\Env;

return [
    // 應(yīng)用地址
    'app_host'         => Env::get('app.host', ''),
    // 應(yīng)用Trace(環(huán)境變量優(yōu)先讀?。?    'app_trace'        => false,
    // 應(yīng)用的命名空間
    'app_namespace'    => '',
    // 是否啟用路由
    'with_route'       => true,
    // 是否啟用事件
    'with_event'       => true,
    // 自動(dòng)多應(yīng)用模式
    'auto_multi_app'   => true,
    // 應(yīng)用映射(自動(dòng)多應(yīng)用模式有效)
    'app_map'          => [],
    // 域名綁定(自動(dòng)多應(yīng)用模式有效)
    'domain_bind'      => [],
    // 禁止URL訪問的應(yīng)用列表(自動(dòng)多應(yīng)用模式有效)
    'deny_app_list'    => [],
    // 默認(rèn)應(yīng)用
    'default_app'      => 'index',
    // 默認(rèn)時(shí)區(qū)
    'default_timezone' => 'Asia/Shanghai',
    // 默認(rèn)驗(yàn)證器
    'default_validate' => '',

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

    // 錯(cuò)誤顯示信息,非調(diào)試模式有效
    'error_message'    => '頁面錯(cuò)誤!請稍后再試~',
    // 顯示錯(cuò)誤信息
    'show_error_msg'   => true,
];

再次修改配置文件,強(qiáng)制路由

<?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>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 應(yīng)用設(shè)置
// +----------------------------------------------------------------------

return [
    // PATHINFO變量名 用于兼容模式
    'var_pathinfo'          => 's',
    // 兼容PATH_INFO獲取
    'pathinfo_fetch'        => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    // pathinfo分隔符
    'pathinfo_depr'         => '/',
    // HTTPS代理標(biāo)識(shí)
    'https_agent_name'      => '',
    // URL偽靜態(tài)后綴
    'url_html_suffix'       => 'html',
    // URL普通方式參數(shù) 用于自動(dòng)生成
    'url_common_param'      => true,
    // 是否開啟路由延遲解析
    'url_lazy_route'        => false,
    // 是否強(qiáng)制使用路由
    'url_route_must'        => true,
    // 合并路由規(guī)則
    'route_rule_merge'      => false,
    // 路由是否完全匹配
    'route_complete_match'  => false,
    // 使用注解路由
    'route_annotation'      => false,
    // 是否開啟路由緩存
    'route_check_cache'     => false,
    // 路由緩存連接參數(shù)
    'route_cache_option'    => [],
    // 路由緩存Key
    'route_check_cache_key' => '',
    // 訪問控制器層名稱
    'controller_layer'      => 'controller',
    // 空控制器名
    'empty_controller'      => 'Error',
    // 是否使用控制器后綴
    'controller_suffix'     => false,
    // 默認(rèn)的路由變量規(guī)則
    'default_route_pattern' => '[\w\.]+',
    // 域名根,如thinkphp.cn
    'url_domain_root'       => '',
    // 是否自動(dòng)轉(zhuǎn)換URL中的控制器和操作名
    'url_convert'           => true,
    // 表單請求類型偽裝變量
    'var_method'            => '_method',
    // 表單ajax偽裝變量
    'var_ajax'              => '_ajax',
    // 表單pjax偽裝變量
    'var_pjax'              => '_pjax',
    // 是否開啟請求緩存 true自動(dòng)緩存 支持設(shè)置請求緩存規(guī)則
    'request_cache'         => false,
    // 請求緩存有效期
    'request_cache_expire'  => null,
    // 全局請求緩存排除規(guī)則
    'request_cache_except'  => [],
    // 默認(rèn)控制器名
    'default_controller'    => 'Index',
    // 默認(rèn)操作名
    'default_action'        => 'index',
    // 操作方法后綴
    'action_suffix'         => '',
    // 默認(rèn)JSONP格式返回的處理方法
    'default_jsonp_handler' => 'jsonpReturn',
    // 默認(rèn)JSONP處理方法
    'var_jsonp_handler'     => 'callback',
];

再次定義admin下的路由

<?php
use think\facade\Route;

// 當(dāng)訪問ming/34 的時(shí)候 路由到index控制器下的index方法,并傳入?yún)?shù)numer=34
Route::rule('ming/:number', 'index/index');

此時(shí)訪問 http://localhost:8082/admin/ming/34

已經(jīng)開始路由

正常訪問

2019-05-25-16-51-03----

沒有路由

此時(shí)開啟強(qiáng)制路由以后,首頁需要開啟路由

由于默認(rèn)的應(yīng)用為index 所以需要在route定義index

目錄如下

2019-05-25-17-11-49----

定義首頁目錄

<?php

use think\facade\Route;

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

此時(shí)訪問首頁
http://localhost:8082/
會(huì)被重定向到 index控制器下的index方法

變量規(guī)則

變量規(guī)則,這里定義的是

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

此時(shí)匹配的是name變量的匹配的規(guī)則,匹配的規(guī)則是雙斜杠

路由規(guī)則

// 定義動(dòng)態(tài)路由
Route::get('hello/:name', 'index/:name/hello');

可以做到把一個(gè)變量傳入另外一個(gè)路由中

路由地址

路由到控制器的操作
添加一個(gè)控制器

2019-05-25-18-47-58----

此控制器使用app\admin\controller 命名空間 其文件內(nèi)容如下

<?php


namespace app\admin\controller;


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

傳入$id作為參數(shù)

再次定義路由規(guī)則如下

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

此時(shí)訪問admin模塊下的blog內(nèi)容,會(huì)匹配:id的內(nèi)容,
http://localhost:8082/admin/blog/23/ 此時(shí)會(huì)匹配23內(nèi)容

其結(jié)果如下


2019-05-25-18-50-16----

路由地址

路由到控制器操作

路由到控制器和操作

上面的例子就是

路由到類的方法

這種方式可以執(zhí)行任何方法

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

上方執(zhí)行的是Blog的read方法或者read的靜態(tài)方法

重定向路由

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

使用302重定向一個(gè)新的地址

路由到模板

使用路由到模板直接渲染

<?php
use think\facade\Route;

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

訪問 http://localhost:8082/admin/blog/ 此時(shí)會(huì)渲染出

2019-05-25-19-32-15----

閉包支持

使用閉包可以使用一些特殊需求的路由,不需要再次執(zhí)行控制器的操作了

<?php
use think\facade\Route;

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

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

2019-05-25-19-50-48----

閉包中可以實(shí)現(xiàn)依賴注入

<?php
use think\facade\Route;

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

此時(shí)由于依賴request會(huì)自動(dòng)注入request

路由參數(shù)

對(duì)當(dāng)前的路由進(jìn)行匹配。。

<?php
use think\facade\Route;

Route::rule('blog/:id', 'blog/read')
    ->ext('html')   // url 后綴檢測
    ->https();  // https 檢測

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

額外追加參數(shù)

使用append額外追加參數(shù)

<?php
use think\facade\Route;

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

此時(shí)會(huì)傳入兩個(gè)參數(shù) app_id 和 status 兩個(gè)參數(shù)

綁定模型

支持綁定模型

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

支持從模型層中直接獲取數(shù)據(jù)

同時(shí)可以使用閉包,獲取數(shù)據(jù)

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秒

路由中間件

可以在路由中,數(shù)據(jù)直接傳給中間件

路由分組

可以對(duì)公有的路由進(jìn)行分組操作

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

此時(shí),可以根據(jù)正則匹配路由

資源路由

<?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');

此時(shí)訪問
http://localhost:8082/admin/blog/34/edit 會(huì)調(diào)用edit方法
http://localhost:8082/admin/blog/34/read 會(huì)調(diào)用read方法

資源嵌套

路由支持資源嵌套

注解路由

修改配置文件,實(shí)現(xiàn)注解路由

<?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>
// +----------------------------------------------------------------------

// +----------------------------------------------------------------------
// | 應(yīng)用設(shè)置
// +----------------------------------------------------------------------

return [
    // PATHINFO變量名 用于兼容模式
    'var_pathinfo'          => 's',
    // 兼容PATH_INFO獲取
    'pathinfo_fetch'        => ['ORIG_PATH_INFO', 'REDIRECT_PATH_INFO', 'REDIRECT_URL'],
    // pathinfo分隔符
    'pathinfo_depr'         => '/',
    // HTTPS代理標(biāo)識(shí)
    'https_agent_name'      => '',
    // URL偽靜態(tài)后綴
    'url_html_suffix'       => 'html',
    // URL普通方式參數(shù) 用于自動(dòng)生成
    'url_common_param'      => true,
    // 是否開啟路由延遲解析
    'url_lazy_route'        => false,
    // 是否強(qiáng)制使用路由
    'url_route_must'        => true,
    // 合并路由規(guī)則
    'route_rule_merge'      => false,
    // 路由是否完全匹配
    'route_complete_match'  => false,
    // 使用注解路由
    'route_annotation'      => true,
    // 是否開啟路由緩存
    'route_check_cache'     => false,
    // 路由緩存連接參數(shù)
    'route_cache_option'    => [],
    // 路由緩存Key
    'route_check_cache_key' => '',
    // 訪問控制器層名稱
    'controller_layer'      => 'controller',
    // 空控制器名
    'empty_controller'      => 'Error',
    // 是否使用控制器后綴
    'controller_suffix'     => false,
    // 默認(rèn)的路由變量規(guī)則
    'default_route_pattern' => '[\w\.]+',
    // 域名根,如thinkphp.cn
    'url_domain_root'       => '',
    // 是否自動(dòng)轉(zhuǎn)換URL中的控制器和操作名
    'url_convert'           => true,
    // 表單請求類型偽裝變量
    'var_method'            => '_method',
    // 表單ajax偽裝變量
    'var_ajax'              => '_ajax',
    // 表單pjax偽裝變量
    'var_pjax'              => '_pjax',
    // 是否開啟請求緩存 true自動(dòng)緩存 支持設(shè)置請求緩存規(guī)則
    'request_cache'         => false,
    // 請求緩存有效期
    'request_cache_expire'  => null,
    // 全局請求緩存排除規(guī)則
    'request_cache_except'  => [],
    // 默認(rèn)控制器名
    'default_controller'    => 'Index',
    // 默認(rèn)操作名
    'default_action'        => 'index',
    // 操作方法后綴
    'action_suffix'         => '',
    // 默認(rèn)JSONP格式返回的處理方法
    'default_jsonp_handler' => 'jsonpReturn',
    // 默認(rèn)JSONP處理方法
    'var_jsonp_handler'     => 'callback',
];

添加注解,實(shí)現(xiàn)路由

<?php
namespace app\controller;

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

    public function read($id)
    {
    }

    public function edit($id)
    {
    }
}

路由綁定

支持綁定到控制器操作,命名空間,和類

// 綁定當(dāng)前的URL到 Blog控制器
Route::bind('blog');
// 綁定當(dāng)前的URL到 Blog控制器的read操作
Route::bind('blog/read');

原先訪問 http://serverName/blog/read/id/5
需要訪問 http://serverName/read/id/5 可以訪問到

剩下的還可以綁定到命名空間 類

域名路由

使用 Route::domain 綁定子域

路由緩存

MISS 路由

MISS路由為全局最后一條執(zhí)行的路由

跨域請求

通過allowCrossDomain 進(jìn)行跨域請求

URL請求

用于生成url請求
路由規(guī)則

<?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;
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容