PHP code example of hehex / hehep-hrouter

1. Go to this page and download the library: Download hehex/hehep-hrouter library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hehex / hehep-hrouter example snippets


$route_conf = [
    // 路由请求定义
    'routeRequest'=>[
        'class'=>'WebRouterRequest',
        'attr1'=>'参数1',
        'attr2'=>'参数2'
    ],
    
    // 路由解析器定义
    'routeMatcher'=>[
        'class'=>'hehe\core\hrouter\fast\FastRouteMatcher',
        'suffix'=>true,// 全局前缀
        'domain'=>false,// 生产url 地址时是否显示域名
        'mergeRule'=>false, // 是否合并路由解析
        'mergeLen'=>0,// 一次合并的条数
        'lazy'=>true,// 是否延迟加载规则
    ],
    
    // 路由缓存配置
    'routeCache' => [
        'routeFile'=>[],// 路由文件
        'cacheDir'=>'',// 缓存目录
        'timeout'=>0,// 缓存过期时间,0表示一直有效
    ],
    
    // 路由规则列表
    'rules'=>[
            // 常规路由规则定义
            '<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
            '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',// 设置id类型
            '<controller:\w+>/<action:\w+>/<id:\d+

use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

// 创建路由管理器对象
$hrouter = new RouteManager([]);

// 设置路由请求,路由解析器
$hrouter->setRouteMatcher([])->setRouteRequest([]);

// 收集路由
Route::get("user/get","user/get");
$hrouter->addRoute("user/<id:\d+>","user/get","get");

// 解析URL地址,并返回结果(假如访问网址"user/123")
$matchingResult = $hrouter->parseRequest();
$action = $matchingResult->getUri();//  获取解析后的"路由地址"
$params = $matchingResult->getParams();// 获取解析后的额外参数
$rule = $matchingResult->getRule();// 获取匹配到的路由规则对象
// $action 结果:user/get,$params: ["id"=>123]

// 生成URL地址
$url = $hrouter->buildUrL("user/get",["id"=>122]);
// $url 结果:user/122


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

// 创建路由管理器对象
$hrouter = Route::intiRoute();

// 设置路由请求,路由解析器
$hrouter->setRouteMatcher([])->setRouteRequest([]);
// Route::intiRoute(AppRouteRequest:class)
// Route::intiRoute('WebRouteRequest')

// 收集路由
Route::get("user/get","user/get");
Route::addRoute("user/<id:\d+>","user/get","get");

// 解析URL地址,并返回结果(假如访问网址"user/123")
$matchingResult = Route::parseRequest();
$action = $matchingResult->getUri();//  获取解析后的"路由地址"
$params = $matchingResult->getParams();// 获取解析后的额外参数
$rule = $matchingResult->getRule();// 获取匹配到的路由规则对象
// $action 结果:user/get,$params: ["id"=>123]

// 生成URL地址
$url = Route::buildUrL("user/get",["id"=>122]);
// $url 结果:user/122


namespace hehe\core\extend;
use hehe\core\hrouter\base\RouteRequest;
use Exception;
use he;

class AppRouteRequest extends RouteRequest
{
    // 定义获取pathinfo 地址的方法
    public function getPathinfo():string
    {
        return he::$ctx->hrequest->getPathInfo();
    }
    
    // 定义获取请求类型的方法
    public function getMethod():string
    {
        return strtolower(he::$ctx->hrequest->getMethod());
    }
    
    // 定义获取host的方法
    public function getHost():string
    {
        return he::$ctx->hrequest->getHostInfo();
    }
}

use hehe\core\hrouter\RouteManager;
use hehe\core\extend\AppRouteRequest;

// 创建路由管理器对象
$hrouter = new RouteManager([]);

// 设置路由请求配置
$hrouter->setRouteRequest([]);

// 创建路由请求对象
$hrouter->createRouteRequest();

// 创建路由请求对象
$routeRequest = new AppRouteRequest();

// 解析URL地址
$matchingResult = $hrouter->parseRequest($routeRequest);

// 获取解析结果
$action = $matchingResult->getUri();//  获取解析后的"路由地址"
$params = $matchingResult->getParams();// 获取解析后的额外参数
$rule = $matchingResult->getRule();// 获取匹配到的路由规则对象


namespace hehe\core\hrouter\fast;

use hehe\core\hrouter\base\RouteRequest;
use hehe\core\hrouter\base\Rule;
use hehe\core\hrouter\Route;
use hehe\core\hrouter\RouteManager;

class FastRouteManager extends RouteManager
{
    // 收集路由规则
    public function addRule(Rule $rule):void
    {
    
    }
    
    // 解析路由请求,调用路由规则
    public function matchRequest(RouteRequest $routeRequest)
    {
    
    }
    
    // 匹配action规则
    public function matchAction(string $uri = '',array $params = [],array $options = [])
    {
    
    }
}


use hehe\core\hrouter\RouteManager;
// 创建路由管理器对象
$hrouter = new RouteManager([]);

$hrouter->setRouteMatcher([
    'class'=>'hehe\core\hrouter\fast\FastRouteMatcher',
    'suffix'=>false,// url 地址后缀
    // url 是否加入域名
    'domain'=>false,// 生产url 地址时是否显示域名,
    // 是否合并路由解析
    'mergeRule'=>false,
    // 一次合并的条数
    'mergeLen'=>0,
    // 是否延迟加载规则
    'lazy'=>true,
]);

// 获取路由解释器对象
$routeMatcher = $hrouter->getRouteMatcher();

// 解析URL地址
$matchingResult = $hrouter->parseRequest();

// 是否匹配成功
$matchingResult->isMatchSuccess();

// 获取解析结果
$action = $matchingResult->getUri();//  获取解析后的"路由地址"
$params = $matchingResult->getParams();// 获取解析后的额外参数
$rule = $matchingResult->getRule();// 获取匹配到的路由规则对象


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

// 设置路由缓存配置
Route::setRouteCache([
    'cacheDir'=>'/www/cache/route',
    'timeout'=>30,
]);

// 获取路由缓存对象
$routeCache = Route::getRouteCache();
$routeCache->addRouteFile('file1','file2');

// 导入路由文件
$routeCache->

use hehe\core\hrouter\Route;

Route::addRoute("user/add","user/doadd");// 任意请求类型
Route::addRoute("user/add","user/doadd","*");// 任意请求类型
Route::addRoute("user/add","user/doadd","get");
Route::addRoute("user/add","user/doadd","get,post");
Route::addRoute("user/add","user/doadd","get|post");
Route::get("user/add","user/doadd");
Route::get("<controller:\w+>/<action:\w+>","<controller>/<action>");


use hehe\core\hrouter\Route;

Route::get("user/<id:\d+>","user/get");
Route::get("user/<id>","user/get")->asParams(["id"=>"\d+"]);
// 正确url地址:user/122,错误url地址:user/add

Route::get("user/<action:\w+>","user/<action>");
// 正确url地址:user/get,user/list,错误url地址:user/123

Route::get("user/<action:get|list>","user/<action>");
// 正确url地址:user/get,user/list,错误url地址:user/edit


use hehe\core\hrouter\Route;

Route::get("user/add/<id:\d+

use hehe\core\hrouter\Route;
$hrouter = new RouteManager();

Route::addGroup("<_ssl:http|https>://www.xxx.cn",function(){
    Route::get("news/list","news/list");
    Route::get("news/get/<id:\d+>","news/get");
})->asDefaults(['ssl'=>'http']);

// 解析http:http://www.xxx.cn/news/list,返回:url:news/news,$params:[]
// 解析http:https://www.xxx.cn/news/get/1,返回:url:news/get,$params:["id"=>1]

$url = $hrouter->buildUrL("news/list");
// $url:http://www.xxx.cn/news/list

$url = $hrouter->buildUrL("news/list",["ssl"=>'https']);
// $url:https://www.xxx.cn/news/list


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;
$hrouter = new RouteManager();

Route::get("<lang:\w+>/news/list","news/list")
            ->asDefaults(['lang'=>'ch']);

// 解析pathinfo:ch/news/list,返回:url:news/list,$params:["lang"=>'ch']
// 解析pathinfo:en/news/list,返回:url:news/list,$params:["lang"=>'en']

$url = $hrouter->buildUrL("news/list",["lang"=>"ch"]);
// $url:ch/news/list

$url = $hrouter->buildUrL("news/list",["lang"=>"en"]);
// $url:en/news/list


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;
$hrouter = new RouteManager();

// 带?问号
Route::get("<lang:\w+/

use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

Route::get('http://www.hehep.cn/news/list','news/list');
Route::get('news/list','news/list')->asDomain("http://www.hehep.cn");

Route::get('http://user<userid:\d+>.hehep.cn/news/<id:\d+>','news/get');
Route::get('news/<id:\d+>','news/get')->asDomain("http://user<userid:\d+>.hehep.cn");

$hrouter = new RouteManager();

$uri = $hrouter->buildUrl('news/list');
// $uri:http://www.hehep.cn/news/list

$uri = $hrouter->buildUrl('news/get',['userid'=>2260,'id'=>1]);
// $uri:http://user2260.hehep.cn/news/1


Route::get("user/add","app/user/AdminController@add");
Route::get("user/<action:\w+>","app/user/AdminController@<action>");

use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

// 设置"路由规则"变量
Route::get("user/<id>","user/get")
    ->asParams(["id"=>"\d+"]);
    
// 设置生成URL后缀,生成的URL地址为:user/{id}.html  
Route::get("user/<id:\d+>","user/get")
    ->asSuffix();

// 设置路由唯一标识,生成地址时,直接使用"news_id"定位此条规则,避免了遍历查找
Route::get("news/<id:\d+>","news/get")
    ->asId("news_id");
    
$htouer = new RouteManager();
/** 使用"news"生成URL地址,最后地址为:"news/122" **/
$htouer->buildUrL("news_id",["id"=>122]);

// 设置默认变量
Route::get("news/list/<page:\d+>","news/list")
    ->asDefaults(["page"=>1]);

Route::get("<language:\w+/

use hehe\core\hrouter\Route;
Route::addGroup("blog",function(){
    Route::addRoute("list","blog/list");
    Route::get("get/<id>","blog/get");
    Route::post("add","blog/doadd");
    Route::get("add","blog/doadd");
});

use hehe\core\hrouter\Route;
Route::addGroup("blog",function(){
    Route::addRoute("list","list");
    Route::get("get/<id>","get")->asParams(["id"=>"\d+"]);
    Route::post("add","doadd");
    Route::get("/hblog/add","doadd");
    Route::get("page","page/list");
})->asPrefix("hblog/");

// 分组后相当于
// Route::addRoute("blog/list","hblog/list");
// Route::get("blog/get/<id:\d+>","hblog/get")->asParams(["id"=>"\d+"]);
// Route::post("blog/add","hblog/doadd");
// Route::get("hblog/add","hblog/doadd");
// Route::get("blog/page","hblog/page/list");


use hehe\core\hrouter\Route;
Route::addGroup("<module:\w+>/blog",function(){
    Route::addRoute("list","list");
    Route::get("get/<id>","get")->asParams(["id"=>"\d+"]);
    Route::post("add","doadd");
    Route::get("/hblog/add","/hblog/doadd");
    Route::get("page","page/list")->asSuffix("shtml");
})->asMethod("get")
    ->asPrefix("<module>/hblog/")
    ->asSuffix("html");

// 分组后相当于
// Route::addRoute("<module:\w+>/blog/list","<module>/hblog/list")->asSuffix("html");
// Route::get("<module:\w+>/blog/get/<id:\d+>","<module>/hblog/get")->asParams(["id"=>"\d+"])->asSuffix("html");
// Route::post("<module:\w+>/blog/add","<module>/hblog/doadd")->asSuffix("html");
// Route::get("hblog/add","hblog/doadd")->asSuffix("html");
// Route::get("<module:\w+>/blog/page","<module>/hblog/page/list")->asSuffix("shtml");


use hehe\core\hrouter\Route;

// 只能相同请求类型的路由规则合并

// get/<id>,geta/<id>,getb/<id> 合并成一条正则表达式进行验证,
Route::addGroup("blog",function(){
    Route::get("get/<id>","get");
    Route::get("geta/<id>","geta");
    Route::get("getb/<id>","getb");
})->asMethod("get")->asParams(["id"=>"\d+"])->asMergeRule();


// 指定路由规则每次合并数量,如合并数量为2时, (get/<id>,geta/<id>)一组合并,(getb/<id>)单独一组,
Route::addGroup("blog",function(){
    Route::get("get/<id>","get");
    Route::get("geta/<id>","geta");
    Route::get("getb/<id>","getb");
})->asMethod("get")->asParams(["id"=>"\d+"])->asMergeRule(2);


use hehe\core\hrouter\Route;
Route::get("http://<language:[a-z]+>.xxx.com/user/get","user/get")
    ->asDefaults(["language"=>'ch']);

Route::get("user/get","user/get")
    ->asDefaults(["language"=>'ch'])->asDomain("http://<language:[a-z]+>.xxx.com");


 Route::addGroup("<_ssl:http|https>://www.xxx.cn",function(){
    Route::get("news/list","news/list");
    Route::get("news/get/<id:\d+>","news/get");
})->asDefaults(['ssl'=>'http']);


use hehe\core\hrouter\Route;

// 动态参数类型,解析的参数格式如下:thread-119781-1-1.html
Route::get([
    'uri'=>'<controller:\w+>/<action:\w+>/thread<param:.*>',
    'action'=>'<controller>/<action>',
    'prule'=>[
        'pvar'=>'param',
        'class'=>'split',// 参数解析器类路径
        'mode'=>'dynamic',// fixed:固定参数,dynamic:动态参数
        // 所有参数的默认值以及顺序,如thread-{id}-{status}-{type}.html
        'names'=>['id','status'=>"0",'type'],
    ]
]);

Route::get('<controller:\w+>/<action:\w+>/thread<param:.*>','<controller>/<action>')
         ->asParamsRule([
            'pvar'=>'param',
            'class'=>'split',
            'mode'=>'fixed',
            'names'=>['id','status'=>"0",'type'] 
        ]);

// URL地址:news/get/thread-119781-1-1.html,$action::news/get,$params:["id"=>119781,"status"=>1,"type"=>1]
// URL地址:news/get/thread-119781.html,$action::news/get,$params:["id"=>119781,"status"=>0]
// 生成URL:["id"=>122,"type"=>1],得到的URL:xxx/thread-122-0-1.html
// 生成URL:["id"=>122],得到的URL:xxx/thread-122-0.html


use hehe\core\hrouter\Route;

Route::get([
    'uri'=>'<controller:\w+>/<action:\w+>/thread<param:.*>',
    'action'=>'<controller>/<action>',
    'prule'=>[
        'pvar'=>'param',
        'class'=>'split',// 参数解析器类路径
        'mode'=>'fixed',// fixed:固定参数,dynamic:动态参数
        // 所有参数的默认值以及顺序,如thread-{id}-{status}-{type}.html
        'names'=>['id','status'=>"0",'type'],
    ]
]);

Route::get('<controller:\w+>/<action:\w+>/thread<param:.*>','<controller>/<action>')
        ->asParamsRule([
            'pvar'=>'param',
            'class'=>'split',
            'mode'=>'fixed',
            'names'=>['id','status'=>"0",'type'] 
        ]);

// URL地址:news/get/thread-119781-1-2.html,$action::news/get,$params:["id"=>119781,"status"=>1,"type"=>2]
// URL地址:news/get/thread-119781-0-1.html,$action::news/get,$params:["id"=>119781,"status"=>0,"type"=>2]
// 生成URL:["id"=>122],得到的URL:xxx/thread-122-0.html
// 生成URL:["id"=>122,"type"=>1],得到的URL:xxxx/thread-122-0-1.html


use hehe\core\hrouter\Route;

// 解析的参数格式如下:news/get/id/1/status/1
Route::get([
    'uri'=>'<controller:\w+>/<action:\w+>/<param:\w+>',
    'action'=>'<controller>/<action>',
    
    'prule'=>[
        'pvar'=>'param',
        'class'=>'pathinfo',// 参数解析器类路径
//        'valueSplit'=>'/',
//        'paramSplit'=>'/',
        // 所有参数的默认值以及顺序
        'names'=>['id','status','type'],
    ]
]);

// 或
Route::get('<controller:\w+>/<action:\w+>/thread<param:.*>','<controller>/<action>')
        ->asParamsRule([
          'pvar'=>'param',
//        'valueSplit'=>'/',
//        'paramSplit'=>'/',
           'names'=>['id','status','type']
         ]);

// URL地址:news/get/id/122/status/1/type/1.html,$action::news/get,$params:["id"=>122,"status"=>1,"type"=>1]
// URL地址:news/get/id/122/type/1.html,$action::news/get,$params:["id"=>122,"type"=>1]
// URL地址:news/get/id/122/status/1.html,$action::news/get,$params:["id"=>122,"status"=>1]

// 生成URL:["id"=>122,"status"=>1],得到的URL:xxx/id/122/status/1
// 生成URL:["id"=>122,"type"=>1,"status"=>1],得到的URL:xxx/id/122/status/1/type/1



use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

Route::get("news/add","news/doadd");
Route::get("news/<id:\d+>","news/get");
Route::get("news/search/conf<params:.*>","news/search")
->asOptions(["prule"=>["pvar"=>"param","class"=>'split','names'=>["catid"=>0,"status"=>0,] ]]);
Route::get("<controller:\w+>/<action:\w+>","<controller>/<action>");

$hrouter = new RouteManager();
$url = $hrouter->buildUrL("news/doadd");
// $url:news/add

$url = $hrouter->buildUrL("news/get",["id"=>1]);
// $url:news/1

$url = $hrouter->buildUrL("news/list",["id"=>1]);
// $url:news/list?id=1

$url = $hrouter->buildUrL("news/search",["catid"=>122,"status"=>1]);
// $url:news/search/conf-122-1


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;
Route::get("news/<id:\d+>","news/get")->asId("news_id");

$hrouter = new RouteManager();
$url = $hrouter->buildUrL("news_id",["id"=>2]);
// $url:news/2


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

Route::get("news/<id:\d+>","news/get")->asSuffix("html");
Route::get("news/list","news/get")->asSuffix();

$hrouter = new RouteManager();
$url = $hrouter->buildUrL("news/get",["id"=>2]);
// $url:news/2.html

$url = $hrouter->buildUrL("news/get.shtml",["id"=>2]);
// $url:news/2.shtml

$url = $hrouter->buildUrL("news/get",["id"=>2],["suffix"=>"shtml"]);
// $url:news/2.shtml

$url = $hrouter->buildUrL("news/list");
// $url:news/list.html

$url = $hrouter->buildUrL("news/list",[],['suffix'=>"shtml"]);
// $url:news/list.shtml


use hehe\core\hrouter\RouteManager;
use hehe\core\hrouter\Route;

Route::get("http://<language:[a-z]+>.xxx.com/user/get","news/get")
    ->asDefaults(["language"=>'ch']);

$hrouter = new RouteManager();
$url = $hrouter->buildUrL("news/get");
// $url:http://ch.xxx.com/user/get


use hehe\core\hrouter\RouteManager;

$hrouter = new RouteManager();
$url = $hrouter->buildUrL("news/get",["#"=>"add"],['suffix'=>"html"]);
// $url:news/get.html#add


use hehe\core\hrouter\Route;
// 指定地址格式
Route::get("blog","blog/index");
Route::get("blog/create","blog/create");
Route::post("blog","blog/save");
Route::get("blog/<id:\d+>","blog/read");
Route::get("blog/<id:\d+>/edit","blog/edit");
Route::put("blog/<id:\d+>","blog/update");
Route::delete("blog/<id:\d+>","blog/delete");


use hehe\core\hrouter\Route;
// 通用格式
Route::get("<controller:\w+>","<controller>/index");
Route::get("<controller:\w+>/create","<controller>/create");
Route::post("<controller:\w+>","<controller>/save");
Route::get("<controller:\w+>/<id:\d+>","<controller>/read");
Route::get("<controller:\w+>/<id:\d+>/edit","<controller>/edit");
Route::put("<controller:\w+>/<id:\d+>","<controller>/update");
Route::delete("<controller:\w+>/<id:\d+>","<controller>/delete");


namespace hrouter\tests\common;
use hehe\core\hrouter\annotation\Restful;
/**
 * @Restful("good")
 */
class GoodController
{
    public function indexAction(){}
    public function createAction(){}
    public function saveAction(){}
    public function readAction(){}
    public function editAction(){}
    public function updateAction(){}
    public function deleteAction(){}
}


namespace hrouter\tests\common;
use hehe\core\hrouter\annotation\Restful;
/**
 * @Restful("<module:\w+>/order")
 */
class OrderController
{
    public function indexAction(){}
    public function createAction(){}
    public function saveAction(){}
    public function readAction(){}
    public function editAction(){}
    public function updateAction(){}
    public function deleteAction(){}
}


namespace hrouter\tests\common;
use hehe\core\hrouter\annotation\Route;
/**
 * @Route("admin")
 * 相当于:Route::addRoute("admin<route:.*

namespace hrouter\tests\common;
use hehe\core\hrouter\annotation\Route;

#[Route("admin")]
class AdminController
{

    /**
     * @Route("doadd")
     * 相当于:Route::addRoute("admin/doadd","admin/add");
     */
    public function addAction(){}

    /**
     * 相当于:Route::addRoute("admin/<id:\d+>","admin/get")->asSuffix("html"); 
     */
     #[Route("/admin/<id:\d+>",suffix:"html")]
    public function getAction(){}
    
    /**
     * 
     * 相当于:Route::addRoute("/admin/dosave","admin/save");  
     */
     #[Route("/admin/save")]
    public function saveAction(){}

}