PHP code example of kode / router

1. Go to this page and download the library: Download kode/router library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

kode / router example snippets




ode\Router\Application;
use Kode\Router\Response;

$app = new Application();

$app->get('/', fn () => Response::html('<h1>Hello kode/router</h1>'), 'home');
$app->get('/hello/{name}', fn (string $name) => "你好,{$name}!", 'hello');
$app->get('/users/{id:\d+}', fn (int $id) => Response::json(['id' => $id]), 'user.show');

$app->send();

$router = new Kode\Router\Router();

// 闭包
$router->get('/ping', fn () => 'pong');

// Class@method(推荐:可缓存)
$router->get('/users/{id}', 'App\Controller\UserController@show', 'user.show');

// 静态方法
$router->get('/health', 'App\Health::check');

// 数组形式
$router->post('/users', [App\Controller\UserController::class, 'store']);

// 可调用对象
$router->get('/stats', App\Action\Stats::class);

// 多方法 / 任意方法
$router->map(['GET', 'POST'], '/form', $handler);
$router->any('/catch-all/{path:.+}', $handler);

$router->get('/posts/{slug}/{page}', $handler, 'post.page')
    ->where('slug', '[a-z0-9\-]+')
    ->where(['page' => '\d+'])
    ->defaults(['page' => 1]);

// 可选段(FastRoute 原生语法)
$router->get('/archive[/{year:\d{4}}]', $handler, 'archive');

$router->get('/users/{id}', $handler);

(new Dispatcher($router->compile()))->match('GET', '/users/a%2Fb')
    ->getParam('id');   // 'a/b' —— 编码态仍是单个段,不会误配成两段路由

$router->group('api', function ($group) {
    $group->prefix('/api/v1');
    $group->middleware(AuthMiddleware::class);

    $group->route(['GET'], '/users', 'App\Api\UserController@index', 'api.users');

    $group->group('admin', function ($sub) {
        $sub->prefix('/admin');
        $sub->route(['GET'], '/stats', 'App\Api\AdminController@stats', 'api.admin.stats');
    });
});

// 把另一个 Router / RouteCollection 挂载进来(模块化拆分)
$router->mount($moduleRouter, '/module', [ModuleMiddleware::class]);

use Kode\Router\Router;
use Kode\Router\Dispatcher;

$router = new Router();
$router->get('/users/{id:\d+}', 'App\Controller\UserController@show', 'user.show');

// —— 编译期:一次性 ——
$compiled = $router->compile();          // CompiledRoutes,不可变
$compiled->count();                      // 路由条数
$compiled->getFingerprint();             // sha256 路由表指纹
$compiled->isCacheable();                // 是否全部可序列化
$payload = $compiled->toArray();         // 纯数组,可 var_export / json_encode

// —— 运行期:每请求 ——
$dispatcher = new Dispatcher($compiled);
$result = $dispatcher->match('GET', '/users/42');

if ($result->isFound()) {
    $result->getName();        // 'user.show'
    $result->getParams();      // ['id' => '42']
    $result->getMiddleware();  // 该路由的中间件栈
    $result->getRouteId();     // 编译期分配的 int 路由 ID
}

$result->isFound();             // 命中
$result->isNotFound();          // 404
$result->isMethodNotAllowed();  // 405,getAllowedMethods() 拿到允许的方法

$body = $dispatcher->handle('GET', '/users/42');   // 未命中抛 RouteNotFoundException

use Kode\Router\Middleware\Pipeline;
use Kode\Router\Middleware\MiddlewareResolver;

// 路由上声明的中间件,运行期会被自动解析并执行
$router->get('/users/{id}', 'App\Controller\UserController@show', 'user.show')
    ->middleware(AuthMiddleware::class, LogMiddleware::class);

$dispatcher = new Dispatcher($router->compile());

// run() = match + 中间件洋葱 + 处理器,未命中抛 RouteNotFoundException
$body = $dispatcher->run('GET', '/users/42');

// 任意中间件只要满足 callable(array $args, callable $next): mixed 即可
final class AuthMiddleware implements Kode\Router\MiddlewareInterface
{
    public function handle(array $args, callable $next): mixed
    {
        // 在 $args 上加工(鉴权、注入上下文……)
        return $next($args);
    }
}

use Kode\Router\Application;
use Kode\Router\Cache\FileRouteCache;

$app = new Application();
$app->setCache(new FileRouteCache(__DIR__ . '/runtime/routes'));


use Kode\Router\Cache\ApcuRouteCache;

if (ApcuRouteCache::isSupported()) {
    $app->setCache(new ApcuRouteCache('kode.router.'));
}

$cache = new FileRouteCache(__DIR__ . '/runtime/routes');

$compiled = $cache->remember('app.routes', fn () => $router->compile());

$cache->has('app.routes');
$cache->forget('app.routes');
$cache->clear();

use Kode\Router\Concurrency\Runtime;

Runtime::detect();            // swoole / swow / fiber / thread / process / fpm / cli
Runtime::host();              // 宿主环境描述
Runtime::inCoroutine();       // 当前是否在协程里
Runtime::supportsFibers();    // PHP 8.1+ 恒为 true
Runtime::isLongRunning();     // 是否常驻内存(决定要不要预热缓存)
Runtime::executionId();       // 当前执行单元 ID(协程/线程/进程唯一)
Runtime::nodeId();            // 节点标识,用于分布式

use Kode\Router\Concurrency\ConcurrentMatcher;

$matcher = new ConcurrentMatcher($dispatcher);

// 批量匹配(纯匹配,不执行处理器)
$results = $matcher->matchAll([
    'a' => ['GET', '/users/1'],
    'b' => ['POST', '/users'],
    'c' => ['GET', '/not-exist'],
]);
// ['a' => MatchResult, 'b' => MatchResult, 'c' => MatchResult]

// 批量执行,限制并发数,异常作为结果值返回
$responses = $matcher->handleAll(
    requests: $requests,
    concurrency: 16,
    captureErrors: true
);

// 匹配后并发执行自定义回调(批量鉴权、批量预取等)
$mapped = $matcher->mapConcurrently(
    $requests,
    fn (MatchResult $result) => $result->isFound() ? $result->getName() : null,
    concurrency: 8
);

// 通用并发工具(任意任务)
$out = ConcurrentMatcher::runTasks([
    'x' => fn () => doSomething(),
    'y' => fn () => doSomethingElse(),
], concurrency: 4, captureErrors: true);

use Kode\Router\Concurrency\RouteContext;

// 框架侧写入(Application 默认已开启,可用 trackContext(false) 关闭)
RouteContext::set($matchResult);

// 业务侧任意深度读取
RouteContext::current();         // ?MatchResult
RouteContext::name();            // 当前路由名
RouteContext::param('id');       // 当前路径参数
RouteContext::has();

// 作用域执行,退出自动还原
$value = RouteContext::run($matchResult, function () {
    return RouteContext::name();
});

// 协程退出时清理,避免长生命周期进程内存堆积
RouteContext::clear();

// master:编译一次,落盘
$router = ', $router->compile());

// worker onStart:读缓存,不编译
$compiled = (new FileRouteCache($dir))->get('app.routes');
$dispatcher = new Dispatcher($compiled);

// worker onRequest:只 match,无状态、无锁
$result = $dispatcher->match($method, $path);

use Kode\Router\Distributed\TraceContext;

// 入口:从上游请求头恢复,没有就新建
$trace = TraceContext::fromHeaders($request->getHeaders());

$trace->getTraceId();       // 32 位 hex,全链路唯一
$trace->getSpanId();        // 16 位 hex,当前跨度
$trace->getParentSpanId();  // 上游跨度
$trace->isSampled();
$trace->isRoot();

// 调用下游:派生子 span 并注入请求头
$child = $trace->child();
$headers = $child->toHeaders();   // ['traceparent' => '00-...', 'tracestate' => '...']

// 写入当前上下文,供日志组件读取
$trace->publish();

use Kode\Router\Distributed\RouteManifest;

$manifest = RouteManifest::fromCompiled($compiled, version: '2.1.0');

$manifest->getFingerprint();        // 完整 sha256
$manifest->getShortFingerprint();   // 前 16 位,日志友好
$manifest->getRouteCount();
$manifest->getNode();

// 随响应下发
foreach ($manifest->toHeaders() as $name => $value) {
    $response = $response->withHeader($name, $value);
}
// X-Kode-Route-Fingerprint / X-Kode-Route-Version / X-Kode-Route-Node

// 网关侧比对
$upstream = RouteManifest::fromHeaders($responseHeaders);

if ($upstream !== null && !$upstream->matches($localManifest)) {
    // 路由表不一致:该节点需要重载
}

// 或直接和本地编译产物比对
$upstream?->matchesCompiled($compiled);

use Kode\Router\Integration\RoutingMiddleware;

$middleware = new RoutingMiddleware($dispatcher);

// 插入任意 PSR-15 管道最前面
$pipeline->pipe($middleware);

final class ControllerHandler implements RequestHandlerInterface
{
    public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $result = RoutingMiddleware::fromRequest($request);

        if ($result === null || !$result->isFound()) {
            return new Response(404);
        }

        // 执行处理器 ...
    }
}

new RoutingMiddleware(
    dispatcher: $dispatcher,
    exposeParams: true,                              // 路径参数逐个写进请求属性
    manifest: RouteManifest::fromCompiled($compiled) // 自动下发路由指纹响应头
);

use Kode\Router\Integration\MiddlewareBridge;

if (MiddlewareBridge::isAvailable()) {
    $pipeline->setMatcher(MiddlewareBridge::matcher($dispatcher));
}

$url = $dispatcher->url('user.show', ['id' => 42]);
// /users/42

$url = $router->url('post.page', ['slug' => 'hello'], ['ref' => 'home']);
// /posts/hello/1?ref=home   (page 走了 defaults)

// 带 basePath
$generator = $router->createUrlGenerator('/app');
$generator->generate('user.show', ['id' => 42]);   // /app/users/42

// 路由级别名
$router->get('/users/{id}', 'App\Controller\UserController@show', 'user.show')
    ->alias('profile', 'member');

// 集合/路由器级别名(指向已存在的命名路由)
$router->alias('account', 'user.show');

// 原名、别名都能生成 URL,结果完全一致
$router->url('user.show', ['id' => 42]);   // /users/42
$router->url('profile',   ['id' => 42]);   // /users/42
$router->url('account',   ['id' => 42]);   // /users/42

// 编译产物里 named 已含别名,运行期无需再查集合
$compiled->getNamed()['profile'];          // 路由 ID

// 1.x 写法,2.0 继续可用
$app = new Application();
$app->get('/users/{id}', $handler, 'user.show');
$app->send();

// 想吃到 2.0 的性能红利,加两行
$app->setCache(new FileRouteCache(__DIR__ . '/runtime/routes'));
$app->boot();