pvettori/router

PHP Router:面向人类的APP路由。

0.1.8 2022-06-25 06:41 UTC

This package is auto-updated.

Last update: 2024-09-25 11:32:35 UTC


README

Latest Version PHP Version MIT License

一个简单的应用路由实用工具。

从本质上讲,Web应用是响应HTTP请求的软件。
这个简单的路由器提供了一种快速简单的方法来定义应用的路线。

内容

  1. 快速开始
    1a. 安装
    1b. 使用示例
  2. 使用
  3. 高级使用
  4. 参考
    4a. PVproject\Routing\Middleware
    4b. PVproject\Routing\Route
    4c. PVproject\Routing\Router

快速开始

安装

composer require pvettori/router

使用示例

use PVproject\Routing\Route;
use PVproject\Routing\Router;

Router::create()->addRoute(Route::get('/home', function () {
    http_response_code(200);
    exit('<h1>Home</h1>');
}))->run();

使用

您可以创建一个路由

$route = Route::get('/home', function () { echo 'This is the home page.'; });

然后将其添加到路由器中

$router = Router::create()->addRoute($route);

最后运行路由器

$router->run();

您可能想要定义一个带有路径参数的路由

$route = Route::get('/path/{param}', function ($param) {
    echo 'This is the route parameter: '.$param;
});

请注意,路径参数会以相同的名称作为参数自动传递给操作函数(没有特定的顺序)。

路径参数也可以通过$parameters参数作为关联数组注入。

或者可以在您的路由操作中访问请求对象(路由器处理PSR-7请求对象)

$route = Route::get('/path', function ($request) {
    echo 'This is the HTTP method: '.$request->getMethod();
});

请注意,任何名为$request的操作函数参数都会自动分配服务器请求对象。

也许您可以定义一个路径前缀供后续路由使用

$router = Router::create()->setPrefix('/admin');
$router->setRoute('/login' function () {
    echo 'This route is /admin/login';
});

高级使用

为了限制路由只响应特定方法,可以将方法数组作为附加参数传递。

$route = Route::create('/path', function () { /* code */ }, ['PUT', 'PATCH']);
// alternative way
$route = Router::create()->setRoute('path/', function () { /* code */ }, ['PUT', 'PATCH']);

路由$action参数接受类方法名称或可调用的类名称(具有魔法方法__invoke()的类)。

$route = Route::get('/path', '\ActionClass->action');
$route = Route::get('/path', '\ActionClass::staticAction');
$route = Route::get('/path', '\InvokableClass');

路由可以分配中间件。
中间件函数和类必须都接受至少两个参数,第一个是服务器请求(由之前的中间件修改),第二个是下一个处理程序。

function middleware_function($request, $handler) {
    // code executed before next handler...
    $response = $handler($request);
    // code executed after next handler...

    return $response;
}

class MiddewareClass extends \PVproject\Routing\Middleware {
    public function __invoke(
        RequestInterface $request,
        callable $handler
    ): ResponseInterface {
        // code executed before next handler...
        $response = $handler($request);
        // code executed after next handler...

        return $response;
    }
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        'middleware_function',
        'MiddewareClass'
    );

中间件可能需要额外的参数。
这些参数可以通过将中间件作为数组输入来传递,其中第一个项目是中间件函数或类,后续项目是精确顺序的额外参数。

function middleware_function($request, $handler, $extra) {
    return $response;
}

$route = Route::create('/path', function ($request) { return $response; })
    ->withMiddleware(
        ['middleware_function', 'extra_argument'],
        'MiddewareClass'
    );

路由也可以按前缀分组

$router = Router::create()->addRouteGroup('/admin', [
    Route::create('/login', function ($request) { return $response; })
    Route::create('/home', function ($request) { return $response; })
], [
    ['middleware_function', 'extra_argument'],
    'MiddewareClass'
]);

可以向路由器提供额外参数。
这些参数会自动注入到路由操作中。

// arguments passed on Router creation
$router = Router::create([
    'arguments' => [
        'extra1' => 'value1',
        'extra2' => 'value2',
    ]
]);
// arguments passed on Router run
$router = Router::create()->run([
    'extra1' => 'value1',
    'extra2' => 'value2',
]);

参考

PVproject\Routing\Middleware

一个抽象类,用于扩展以帮助创建中间件类。

中间件方法

__invoke(RequestInterface $request, callable $handler): ResponseInterface

中间件类的唯一必需方法。

PVproject\Routing\Route

代表单个路由的类。
路由对象是不可变的。

路由方法

__construct(string $path, $action, [array $methods], [string $name])

创建一个新的路由。

getAction(): callable

返回路由操作函数。

getAttributes(): array

返回路由属性。

getMetohds(): array

返回路由方法。

getMiddleware(): array

返回路由中间件。

getName(): ?string

返回路由名称。

getPath(): string

返回声明的路由路径。

matches(RequestInterface $request, [array &$pathParams]): bool

检查路由是否匹配给定的请求对象。

withAttributes(array $attributes): Route

返回一个带有附加属性的新实例。
属性通过名称作为参数传递给操作。

withMiddleware($middleware [, $middleware] [, ...])

返回一个具有分配中间件的新路由对象。

withName(string $name): Route

返回一个新的具有指定名称的路由对象。

withPath(string $path): Route

返回一个新的具有指定路径的路由对象。

路由 工厂方法

Route::create(string $path, $action, [array $methods])

创建一个新的路由。

Route::get(string $path, $action)

创建一个新的具有 "GET" 方法的路由。

Route::put(string $path, $action)

创建一个新的具有 "PUT" 方法的路由。

Route::post(string $path, $action)

创建一个新的具有 "POST" 方法的路由。

Route::patch(string $path, $action)

创建一个新的具有 "PATCH" 方法的路由。

Route::delete(string $path, $action)

创建一个新的具有 "DELETE" 方法的路由。

PVproject\Routing\Router

路由类。

路由器 方法

__construct([array $config])

创建一个新的路由器。

getRoute(string $name): ?Route

获取一个命名路由。

getRoutes(): array

获取已定义的路由。

run([array $arguments])

运行路由器。

setPrefix([string $prefix]): Router

设置路由前缀。该前缀将添加到后续每个路由的路径之前。
在此方法之前声明的路由不受影响。

setFallback($action): Router

设置一个当没有路由匹配时执行的动作。

addRoute(Route $route): Router

添加一个路由。

addRouteGroup(string $prefix, array $routes, [array $middleware]): Router

添加多个按前缀分组的路由。
先前声明的前缀将添加到组前缀之前。
后续路由不受组前缀的影响。

run([array $arguments])

执行路由匹配。

setRoute(string $path, $action, [array $methods], [string $name]): Route

添加一个路由并返回路由对象。
有关详细信息,请参阅 Route::__construct()

路由器 工厂方法

Router::create([array $config])

创建一个新的路由器。