andrewcarteruk/simple-route

FastRoute 包的简单易用封装器

v0.3.0 2016-06-15 11:13 UTC

This package is auto-updated.

Last update: 2024-09-19 13:17:25 UTC


README

Build Status Code Coverage Scrutinizer Code Quality Latest Stable Version Total Downloads License

这个简单易用的路由器是对FastRoute库的一个简单封装。

AndrewCarterUK (Twitter) 提供

安装

使用 Composer 安装。

composer require andrewcarteruk/simple-route ^0.2

示例用法

use SimpleRoute\Route;
use SimpleRoute\Router;

$router = Router::fromArray([
    new Route('GET', '/', 'handler1'),
    new Route('GET', '/{page}', 'handler2'),
]);

try {
    $result = $router->match($_SERVER['REQUEST_METHOD'], $_SERVER['REQUEST_URI']);

    $handler = $result->getHandler();
    $params = $result->getParams();

    // ...
} catch (SimpleRoute\Exception\NotFoundException $exception) {
    // ...
} catch (SimpleRoute\Exception\MethodNotAllowedException $exception) {
    // ...
}

文档

以下文档来自 FastRoute 文档。

路由定义为一个数组,该数组包含 SimpleRoute\Route 对象,这些对象被传递给 SimpleRoute\Router::fromArray(array $routes)

SimpleRoute\Route 对象需要 $method$pattern$handler

$route = new Route($method, $pattern, $handler);

$method 是一个大写 HTTP 方法字符串,表示某个路由应该匹配的方法。可以使用数组指定多个有效的方法。

$routes = [
    // This route
    new Route(['GET', 'POST'], '/test', 'handler'),

    // Is equivalent to these two routes together
    new Route('GET', '/test', 'handler'),
    new Route('POST', '/test', 'handler'),
];

默认情况下,$pattern 使用一种语法,其中 {foo} 指定一个名为 foo 的占位符,并匹配正则表达式 [^/]+。要调整占位符匹配的模式,可以指定一个自定义模式,例如 {bar:[0-9]+}

一些示例

$routes = [
    // Matches /user/42, but not /user/xyz
    new Route('GET', '/user/{id:\d+}', 'handler'),

    // Matches /user/foobar, but not /user/foo/bar
    new Route('GET', '/user/{name}', 'handler'),

    // Matches /user/foo/bar as well
    new Route('GET', '/user/{name:.+}', 'handler'),
];

自定义路由占位符的模式不能使用捕获组。例如 {lang:(en|de)} 不是一个有效的占位符,因为 () 是一个捕获组。相反,可以使用 {lang:en|de}{lang:(?:en|de)}

此外,括号 [...] 内的路由部分被认为是可选的,因此 /foo[bar] 将匹配 /foo/foobar。可选部分仅支持在末尾位置,不支持在路由中间。

$routes = [
    // This route
    new Route('GET', '/user/{id:\d+}[/{name}]', 'handler'),

    // Is equivalent to these two routes together
    new Route('GET', '/user/{id:\d+}', 'handler'),
    new Route('GET', '/user/{id:\d+}/{name}', 'handler'),

    // This route is NOT valid, because optional parts can only occur at the end
    new Route('GET', '/user[/{id:\d+}]/{name}', 'handler'),
];

$handler 参数不一定是回调,它也可以是控制器类名或任何其他您希望与路由关联的数据。SimpleRoute 只会告诉您哪个处理程序对应于您的 URI,如何解释它取决于您。

致谢

这个库仅仅是 FastRoute 的一个封装,旨在提供一个更易用的 API。

FastRoute 的作者是 Nikita Popov