karelwinterskyarris.router

Arris 应用 µ框架 - AppRouter 类

1.100.4 2024-09-20 15:29 UTC

This package is auto-updated.

Last update: 2024-09-20 15:30:56 UTC


README

尝试基于 https://github.com/nikic/FastRoute 编写自己的路由器

实现静态类 AppRouter,具有以下方法

  • init()
  • get()
  • post()
  • 等等

将其作为一个独立包提出,以便可以单独更新主框架类和单独连接。

初始化

AppRouter::init(AppLogger::scope('routing'), [
// опции
]);

选项

  • defaultNamespace - 默认命名空间
  • namespace - defaultNamespace 的别名
  • prefix - 当前 URL 前缀(类似于组的处理方式)
  • routeReplacePattern - ?
  • allowEmptyHandlers (false) - 允许空(定义为 [])处理器吗?如果为 false - 抛出异常 AppRouterHandlerError: Handler not found or empty
  • allowEmptyGroups (false) - 是否允许空组?空组指的是没有路由的组。如果允许 - 对于此类组将解析中间件和选项。

需要注意的是,"空"处理器可以以两种方式描述

  • null - 这样的处理器会被简单地忽略,在这种情况下,路由将返回 AppRouter::NotFoundException: URL not found
  • [] - 行为取决于 allowEmptyHandlers 选项
    • = true - 处理器不执行任何操作,尽管中间件链会通过它
    • = false - 抛出异常 AppRouterHandlerError - Handler not found or empty
AppRouter::get('/', function () {
    CLIConsole::say('Call from /');
}, 'root');

AppRouter::group([
    'prefix' => '/auth', 
    'namespace' => 'Auth', 
    'before' => static function () { CLIConsole::say('Called BEFORE middleware for /auth/*'); }, 
    'after' => null
    ], static function() {

    AppRouter::get('/login', function () {
        CLIConsole::say('Call /auth/login');
    });

    AppRouter::group(['prefix' => '/ajax'], static function() {

        AppRouter::get('/getKey', function (){
            CLIConsole::say('Call from /test/ajax/getKey');
        }, 'auth:ajax:getKey');

    });

    AppRouter::get('/get', function (){
        CLIConsole::say('Call from /test/get (declared after /ajax prefix group');
    });

    AppRouter::group(['prefix' => '/2'], static function() {
        AppRouter::get('/3', function () {
            CLIConsole::say('Call from /test/2/3');
        });
    });

});

AppRouter::get('/root', function (){
    CLIConsole::say('Call from /root (declared after /ajax prefix group ; after /test prefix group)');
});

AppRouter::group([], function (){
    AppRouter::get('/not_group', function () {

    });
});

异常(Exceptions)

类抛出三个异常

  • AppRouterHandlerError - 处理器错误(空的、不正确的等)
  • AppRouterNotFoundException - 路由未定义(URL ... not found)
  • AppRouterMethodNotAllowedException - 使用的方法对于此路由不可用

在这种情况下,会传递有关路由的扩展信息,可以通过方法 $e->getError() 获取这些信息,因为无法重写最终方法 getMessage()

待办事项

  • init() 添加 middlewareNamespace 选项 - 默认中间件命名空间。