zeroframe/zerorouter

基于PSR-7的PHP轻量级且非常快的路由器,能够混合不同的策略。

0.0.1 2018-09-14 17:11 UTC

This package is auto-updated.

Last update: 2024-09-29 04:09:05 UTC


README

这是一个 轻量级且非常快的路由器,能够混合不同的策略,你也可以实现自己的策略。
路由器基于 PSR-7,我们建议使用快速实现,如 nyholm/psr7 和 nyholm/psr7-server。
你可以将此路由器用于你的 中间件 或作为独立组件。

主要目标是给问题一个线性复杂度,并且如 PrefixBlockLookupStrategySuffixBlockLookupStrategy 这样的策略可以很好地达到这个目标。

以下是对每种策略的解释。

HeaderKeyLookupStrategy

跳过所有策略,并使用头部键X-Routing-Key直接匹配你的路由并获取最佳性能。在微服务和大型动态映射中可能很有用。

仅支持动态路由。

PrefixBlockLookupStrategy

这种策略将URL按块分割,每个块由一个'/'分隔。我们只在前面的静态路由部分之前创建映射。

示例

路由:/comments/sport/{id}

映射:[ 'comments' => [ 'sport' => [ 'regsex' => [...] ] ] ]

这种策略将直接在数组映射中尝试查找每个块,如果找不到块,则尝试检查最后找到的块中是否存在节点"regsex",然后尝试匹配正则表达式。使用这种策略,你可以拥有大型动态映射而不会出现性能问题,因为数组访问非常快,并且每次访问时你都限制了数据为几个正则表达式。

以下面的URL为例:/comments/sport/8041984,PrefixBlockLookupStrategy将执行以下步骤

  • 使用'comments'键访问数组 [ 成功 ]
  • 使用'sport'键访问数组 [ 成功 ]
  • 使用'8041984'键访问数组 [ 失败 ]
  • 尝试匹配最后找到的块上的正则表达式,在这种情况下,我们的块是'sport'。

处理静态部分在动态路由之前的URL

/users/{id} /users/comments/{id} /profiles/{activity}/id

SuffixBlockLookupStrategy

使用与PrefixBlockLookupStrategy相同的策略,但顺序相反,仅在工作于后缀。

处理静态部分在动态路由之后的URL

/{id}/users /{id}/comments/users /{id}/{activity}/profiles

StaticKeyLookupStrategy

静态路由的基本且最佳策略。

/dummy
/php
/dave

GenericBlockRegexLookupStrategy

这种策略尝试匹配仅包含动态路由的正则表达式,通用正则表达式只包含URL中的动态部分而没有静态部分。

使用composer安装

$ composer require zeroframe/zerorouter

基本用法

<?php
require 'vendor/autoload.php';

$router = new \Zeroframe\Zerorouter\Router(
    (new \Zeroframe\Zerorouter\RouterMap(
        function (\Zeroframe\Zerorouter\RouterMap $routerMap) {
            $routerMap->all('/');
            $routerMap->all('/{user}');
            $routerMap->all('/dummy/{bookmarks}');
            $routerMap->all('/{page}/category');
        },
        // enable cache only in production
        false,
        // cache file path
        ''
    // here you can add strategy, the order gives the priority and you are free to remove or add new strategies
    ))->addStrategy(new \Zeroframe\Zerorouter\Lookups\HeaderKeyLookupStrategy())
    ->addStrategy(new \Zeroframe\Zerorouter\Lookups\StaticKeyLookupStrategy())
    ->addStrategy(new \Zeroframe\Zerorouter\Lookups\PrefixBlockLookupStrategy())
    ->addStrategy(new \Zeroframe\Zerorouter\Lookups\SuffixBlockLookupStrategy())
    ->addStrategy(new \Zeroframe\Zerorouter\Lookups\GenericBlockRegexLookupStrategy())
);

$psr17 = new \Nyholm\Psr7\Factory\Psr17Factory();
$request = (new \Nyholm\Psr7Server\ServerRequestCreator(
    $psr17,
    $psr17,
    $psr17,
    $psr17
))->fromGlobals();

var_dump($router->dispatch($request));