igorcrevar/icrouter

针对标准路由问题的不同方法。基于匹配树。

dev-master 2015-04-16 18:11 UTC

This package is not auto-updated.

Last update: 2024-10-02 09:05:57 UTC


README

#icRouter 针对标准路由问题的不同方法。不使用正则表达式,而是构建匹配树。

此库不与旧版本的PHP兼容。最低版本为5.3

用法

使用

use IgorCrevar\icRouter\Router;
use IgorCrevar\icRouter\Route;
use IgorCrevar\icRouter\Interfaces\DefImpl\DefaultNodeBuilder;

创建路由器

$router = new Router(new DefaultNodeBuilder());

添加一些路由

$router->setRoutes([
    new Route('simple', '/simple', 
              array('module' => 'simple')),
    new Route('simple_param', '/param/:a', 
              array('module' => 'simple_param', 'a' => 10), 
              array('a' => '\d+')), // a is integer
    new Route('two_params', '/param/hello/:a/some/:b', 
              array('module' => 'two_params', 'a' => 10, 'onemore' => 'time')),
    new Route('two_params_any', '/home/hello/:a/:b/*', 
              array('module' => 'two_params_any', 'a' => 10, 'b' => '10'),
              array('b' => '[01]+')), // b is string / number of 0' and 1'
    new Route('complex_param', '/complex/id_:id',
              array('module' => 'complex_param'),
              array('id' => '\d+')),
    new Route('home', '/*', 
              array('module' => 'home')),
]);

构建路由树

$router->build();

匹配

$result = $router->match('/a/b/c/d/e');

如果路由存在,则$result将为匹配参数的数组(键值对),否则返回false

生成

$result = $router->generate('two_params', array('b' => 'aabb'));

第一个参数是路由名称,第二个是参数(键值对)数组

路由构造函数参数

  • 路由名称
  • 模式:示例
    1. /acount/:id/* - 提供了额外参数的功能
    2. /account/:id/:action
    3. /account/id_:id 参数指定为 /:[A-Za-z0-9]+/ 每个路由段只允许一个参数
  • 路由的默认参数(键-值对)
  • 模式中参数的可选正则表达式 示例
    1. array('id' => '\d+') - id是整数
    2. array('type' => 'car|boat|plane') - 类型是汽车、船只或飞机之一

提示

对于生产环境,因为 $router->build() 费时,你应该缓存已构建的路由器(APC、序列化等...)

单元测试

进入基本目录并执行

phpunit test/RouterTest.php

待办事项

在此库与一些正则表达式路由库(如symfony框架中的库)之间的性能基准测试
例如。