thruster/http-router

Thruster HttpRouter 组件(基于 PSR-7 和 FastRoute 的路由器)

1.1.0 2016-05-31 12:04 UTC

This package is auto-updated.

Last update: 2024-09-14 02:53:19 UTC


README

[最新版本] (https://github.com/ThrusterIO/http-router/releases) [软件许可证] (LICENSE) [构建状态] (https://travis-ci.org/ThrusterIO/http-router) [代码覆盖率] (https://scrutinizer-ci.com/g/ThrusterIO/http-router) [质量评分] (https://scrutinizer-ci.com/g/ThrusterIO/http-router) [总下载量] (https://packagist.org.cn/packages/thruster/http-router)

[电子邮件] (mailto:team@thruster.io)

Thruster HttpRoute 组件。基于 PSR-7 和 FastRoute 的简单路由器。

安装

通过 Composer

$ composer require thruster/http-router

用法

独立使用

<?php

use Psr\Http\Message\RequestInterface;
use Thruster\Component\HttpRouter\Router;
use Thruster\Component\HttpRouter\RouteProvider;

$application = new class implements RouteProvider {
    public function getRoutes() : array
    {
        return [
            'hello_world' => ['GET', '/', 'hello'],
            ['POST', '/', [$this, 'foo']]
        ];
    }

    public function hello(ServerRequestInterface $request)
    {
        // return new Response(200, [], 'Hello world');
    }

    public function foo(ServerRequestInterface $request)
    {
        // return new Response(404, [], 'Foo Bar');
    }
};


$router = new Router($application);
$response = $router->handleRequest(ServerRequest::fromGlobals()); // PSR-7 Response

PSR-7 风格的中间件

<?php

use Psr\Http\Message\RequestInterface;
use Thruster\Component\HttpRouter\Router;
use Thruster\Component\HttpRouter\RouteProvider;
use Thruster\Component\HttpRouter\RouteHandler;

$application = new class implements RouteProvider, RouteHandler {
    public function getRoutes() : array
    {
        return [
            'hello_world' => ['GET', '/', 'hello'],
            ['POST', '/', [$this, 'foo']]
        ];
    }

    public function handleRoute(
    	ServerRequestInterface $request,
    	ResponseInterface $response,
    	callable $actionHandler
    ) : ResponseInterface {
    	// ... call actionHandler and return ResponseInterface
    }

    public function handleRouteMethodNotAllowed(
    	ServerRequestInterface $request,
    	ResponseInterface $response,
    	array $allowedMethods
    ) : ResponseInterface {
    	// ... handle method not allowed error
    }

    public function handleRouteNotFound(
    	ServerRequestInterface $request,
    	ResponseInterface $response
    ) : ResponseInterface {
    	// ... handle route not found (404)
    }
};


$router = new Router($application, $application);
$response = $router(ServerRequest::fromGlobals(), new Response()); // PSR-7 Response

测试

$ composer test

贡献

请参阅 CONTRIBUTINGCONDUCT 以获取详细信息。

许可证

请参阅许可文件获取更多信息。