niahoo/altorouter

PHP的闪电路由器

dev-master 2014-01-08 13:47 UTC

This package is not auto-updated.

Last update: 2024-09-14 14:41:32 UTC


README

AltoRouter 是一个轻量但强大的 PHP 5.3+ 路由类,受到了 klein.php 的强烈启发。

  • 动态路由,支持命名参数
  • 反向路由
  • 灵活的正则表达式路由(受 Sinatra 启发)
  • 自定义正则表达式

入门指南

  1. 需要 PHP 5.3.x
  2. 使用 Composer 或手动安装 AltoRouter
  3. 设置 URL 重写,以便所有请求都由 index.php 处理
  4. 创建一个 AltoRouter 实例,映射你的路由并匹配一个请求。
  5. 查看示例 index.php 文件,以更好地了解如何使用 AltoRouter(index.php)。

路由

$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in

// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');

// reversed routing
$router->generate('users_show', array('id' => 5));

你可以在你的命名参数上使用以下限制。AltoRouter 将为你创建正确的正则表达式。

*                    // Match all request URIs
[i]                  // Match an integer
[i:id]               // Match an integer as 'id'
[a:action]           // Match alphanumeric characters as 'action'
[h:key]              // Match hexadecimal characters as 'key'
[:action]            // Match anything up to the next / or end of the URI as 'action'
[create|edit:action] // Match either 'create' or 'edit' as 'action'
[*]                  // Catch all (lazy, stops at the next trailing slash)
[*:trailing]         // Catch all as 'trailing' (lazy)
[**:trailing]        // Catch all (possessive - will match the rest of the URI)
.[:format]?          // Match an optional parameter 'format' - a / or . before the block is also optional

一些更复杂的示例

@/(?[A-Za-z]{2}_[A-Za-z]{2})$ // custom regex, matches language codes like "en_us" etc.
/posts/[*:title][i:id]        // Matches "/posts/this-is-a-title-123"
/output.[xml|json:format]?    // Matches "/output", "output.xml", "output.json"
/[:controller]?/[:action]?    // Matches the typical /controller/action format

冒号前的字符(匹配类型)是以下正则表达式之一的一个快捷方式

'i'  => '[0-9]++'
'a'  => '[0-9A-Za-z]++'
'h'  => '[0-9A-Fa-f]++'
'*'  => '.+?'
'**' => '.++'
''   => '[^/\.]++'

可以使用 addMatchTypes() 方法添加新的匹配类型

$router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?'));

贡献者

许可证

(MIT 许可证)

版权所有 (c) 2012-2013 Danny van Kooten hi@dannyvankooten.com

特此授予任何人免费获得本软件及其相关文档副本(“软件”)的副本的权限,可以在不受限制的情况下处理软件,包括但不限于使用、复制、修改、合并、发布、分发、再许可和/或出售软件的副本,并允许向软件提供副本的个人这样做,前提是符合以下条件

上述版权声明和本许可声明应包含在软件的所有副本或实质性部分中。

本软件按“原样”提供,不提供任何明示或暗示的保证,包括但不限于适销性、适用于特定目的和不侵犯专利的保证。在任何情况下,作者或版权所有者均不对任何索赔、损害或其他责任负责,无论源于合同、侵权或其他方式,与软件或其使用或其他交易有关。