mnavarrocarter/amp-http-router

PHP中Amp应用程序的基于可组合中间件的路由引擎

0.1.0 2020-09-05 15:35 UTC

This package is auto-updated.

Last update: 2024-09-06 00:30:49 UTC


README

这是一个高性能的路由引擎,它处理Amp HTTP服务器的请求,灵感来源于Express JS。

安装

composer require mnavarrocarter/amp-http-router

快速开始

<?php
declare(strict_types=1);

use Amp\Http\Server\Request;
use Amp\Http\Server\Response;
use MNC\Router\Router;
use MNC\Router\RoutingContext;
use function MNC\Router\handleFunc;
use function MNC\Router\html;
use function MNC\Router\listenAndServe;

function homepage(): Response {
    return html('Hello world!');
}

function findUser(Request $request): Response {
    $id = RoutingContext::of($request)->getParam('id');
    return html(sprintf('The user id is %s', $id));
}

$router = Router::create();
$router->get('/', handleFunc('homepage'));
$router->get('/users/:id', handleFunc('findUser'));

Amp\Loop::run(fn() => yield listenAndServe('0.0.0.0:8000', $router));

路由组合

你可以将多个路由器挂载到不同的路径上,以实现更有效的路由。

<?php

use MNC\Router\Router;

$app = Router::create();
// Define main app routes

$api = Router::create();
// Define api routes

// Api routes will be under `/api`
$app->mount('/api', $api);