flatpixels/light-route

一个简单易用的PHP路由器。

0.0.1 2018-12-28 14:03 UTC

This package is auto-updated.

Last update: 2024-09-29 05:02:18 UTC


README

此库提供简单的路由配置及其路由。

安装

composer require flatpixels/light-route

用法

首先,您必须通过以下方式设置您的路由:

  • 获取路由器实例
$router = LightRoute\LightRouter::getInstance();
  • 将您的路由注册到路由器中
$router->addRoute('get', '/posts/', function(){
    echo "Welcome to the posts page";
});

现在,您已经配置了路由,您必须通过调用解析器来解析当前用户请求URI

$router->resolve();

将路由注册到路由器中

使用方法 addRoute(string $requestMethod, $string requestUrl, callable $callable, [, string $routeName ]) 将路由添加到路由器。该方法接受4个参数

  • $requestMethod : 设置用户请求方法。仅支持:GET、POST。
  • $requestUrl : 设置请求URL,该URL将解析路由。
  • $callable : 一个回调,用于定义当路由到达时执行的操作。
  • $routeName : (可选) 设置路由的名称。

使用参数注册路由

您可以通过使用表示法 :paramName 将数据传递到其URL中来注册路由。示例

$route->addRoute('get', 'post/:id', function($id) {
    echo "Show the post: " . $id;
});

在下面的代码中,我通过将 id 传递到其URL中设置了一个路由。

您可以传递尽可能多的数据

$route->addRoute('get', 'post/:id/:slug/:author', function($id, $slug, $author) {
    echo "Show the post: " . $id;
    echo "With the slug: " . $slug;
    echo "Written by: " . $author;
});

具有参数验证的路由

通过将参数传递到路由URL中,您可以使用 format(array $paramsValidators) 方法设置验证约束

$route->addRoute('get', 'post/:id', function($id) {
    echo "Show the post: " . $id;
})->format(['id' => "[0-9]"]);

format(...) 方法接受一个键值对数组 $key => $value,其中 $key 是参数名称,而 $value 是表示该参数有效值的正则表达式。

重定向到特定路由

您可以通过调用 redirect(..) 方法来使用路由器,将您重定向到另一个路由。该方法接受2个参数

  • $routeName : 我们必须重定向到的路由的名称。
  • $params : (可选) 一个数组,其中 $key => $value,其中 $key 是参数名称,而 $value 是参数的值
$router->addRoute('get', '/go/to/single', function() use($router){

    //Redirect to the "single_post" route, with param: id=4
    $router->redirect('single_post', ['id' => 4]);
});