wok/router

WOK 路由组件

v0.4.1 2017-03-30 11:45 UTC

This package is auto-updated.

Last update: 2024-09-25 07:48:02 UTC


README

此库提供了一个基于正则表达式的轻量级路由器。

SensioLabsInsight

免责声明:此组件是WOK(Web 操作套件)框架的一部分。然而,它也可以作为一个独立的库使用。

安装

建议使用 Composer 将该组件安装为依赖项。

composer require wok/router

由于此包没有依赖项,您也可以使用 git 或通过 直接下载 来获取它。

git clone https://github.com/web-operational-kit/router.git

功能

与其他路由器一样,以下功能可用

  • 使用方法和URI进行路由(请参阅使用部分)
  • 替换和匹配路由参数
  • 之后可以操作路由定义
  • 独立检索路由元数据
  • 操作路由集合

注意:由于该库的简单性和独立性愿望,目前不会实现某些功能。

因此,分发器不会执行任何函数。它只返回第一个匹配的路由及其所需的信息。

自己做出判断吧 :)

基本用法

use \WOK\Router\Route;
use \WOK\Router\Collection;

// First instanciate a collection
$collection = new Collection();

$collection = new Collection();
$collection->addRoute(
    new Route(
        ['POST', 'GET', 'HEAD'],// Define the accepted HTTP methods
        '/path/to/the/{resource}', // Define the route URI
        [ // Define the URI parameters
            'resource'  => '[a-z0-9\-]+'
        ]
    ),
    'Controller::action', // Define the target (function name, class, object, array, Closure, ...)
    'Controller->Action' // Define the route name
);

// Define many other routes ...


// Retrieve the first matching route
try {

    $route = $collection->match('GET', '/path/to/the/resource-file-name');

}

// No route match the current request
catch(\DomainException $e) {

    $route = (object) array(
        'name'          => 'Controller->pageNotFound',
        'action'        => ['Controller', 'pageNotFound'],
        'parameters'    => []
    );

}

// Play with the route value
call_user_func_array($route->action, $route->parameters);

警告:为了避免任何无聊的返回值,如果找不到路由,则Collection::match会抛出DomainException

这样,您可以自由定义任何未找到的行为