适用于几乎所有情况的非常简单的路由器。

dev-master 2018-04-30 19:07 UTC

This package is not auto-updated.

Last update: 2024-09-20 00:27:17 UTC


README

非常简单的适用于几乎所有情况的URL路由器。

它将当前请求与一组预定义的路由进行匹配。如果匹配成功,它将返回一个 VanGestelJasper\Router\Route 实例。如果匹配失败,它将返回 null。

Route 实例包含请求的所有数据,包括

  • 头部
  • URL
  • 路径
  • 方法
  • 查询
  • 有效载荷

...,以及您为其设置的处理器、名称和中间件。

注意: 这个小库还处于非常早期的阶段。

用法

示例

use \VanGestelJasper\Router\Router;

// instantiate the router
$router = new Router;

// Add routes
$router->get('/', 'PageController@index');
$router->get('/projects/{slug}', function($route) { /* ... */ });

// Optional: Add a name to the route. This name will be available on the route object.
$router
    ->post('/uploads', 'UploadController@create')
    ->name('uploads-route')
    ->use('UploadMiddleware');
// The `use` method is for running middleware before the route handler is called.
// You can chain `use` calls like `->use('...')->use('...');` to add multiple.
// The router will call the `run` method on the class you provide.
// If `run` returns true, the next middleware will be called or the route handler
// when there is no further middleware.
// You can do anything to the $route object inside the middleware.
// Returning anything else then true will stop the router.
// You should handle termination yourself.

// Optional: Define a fallback route in case no route matches.
$router->fallback('ErrorController@NoMatch');

// Returns the matched route or null
// You can modify the route however you want
$route = $router->dispatch();

// Optional: If you just need the matched route object, then you don't need this next method.

// This will trigger the matched route handler for you.
// If there was no matching route, the fallback route will be used if you defined it.
// The route handler will be called with the $route as parameter.
// The return value of Router->run() is a `true` if a handler got triggered, `false` if not.
$ran = $router->run();

中间件示例

class UploadMiddleware {

    /**
     * Run middleware.
     * @param \VanGestelJasper\Router\Route $route
     * @return bool $next
     */
    public function run($route): bool
    {
        // manipulate the $route here
        // or anything else oyu need to do

        return true // go to next middleware or run route handler
        return false // stop the router
    }
}

注意:目前不支持像路由处理器那样将中间件作为闭包运行。

如果URL是 localhost:5000/projects/test?page=1,则上面示例中的 $router->dispatch() 的示例返回值

VanGestelJasper\Router\Route Object (
    [handler] => ProjectController@show
    [name] => The route name
    [request] => VanGestelJasper\Router\Request Object (
        [headers] => Array (
            [cache-control] => no-cache
            [Accept] => */*
            [Host] => localhost:5000
            [accept-encoding] => gzip, deflate
            [Connection] => keep-alive
        )
        [url] => https://:5000/projects/jasper
        [path] => /projects/test
        [method] => GET
        [query] => VanGestelJasper\Router\Query Object (
            [page] => 1
        )
        [payload] => VanGestelJasper\Router\Payload Object (
            [slug] => test
        )
    )
    [middleware] => Array ()
)

如示例所示,您可以提供函数回调或形如 Class@method 的字符串。 VanGestelJasper\Router\Router->dispatch() 将始终以匹配的路由作为第一个参数触发处理器。

请看下面的示例。

class RouteHandler {
    /**
     * @param VanGestelJasper\Router\Route $route
     */
    public function handle($route)
    {
        /* ... */
    }
}

$router = new VanGestelJasper\Router\Router;

$router->get('/foo', 'RouteHandler@handle');
$router->get('/bar', function($route) {
    /* ... */
});

$router->dispatch();
$router->run();

请求数据

请求数据将以JSON格式读取。如果成功,您将能够在 Route -> Request -> Payload 对象中访问它。

请看下面的示例结果。

注意: 路由中定义的 {} 之间的通配符也将可在 Route -> Request -> Payload 对象中访问。

示例

$router = new VanGestelJasper\Router\Router;
$route->post('/projects/{slug}', 'ProjectController@create');
$route = $router->dispatch();

print_r($route);

// the request url is: POST https://example.com/projects/test
// the request data is:
// {
//     "title": "PHP",
//     "subtitle": "Router"
// }
VanGestelJasper\Router\Route Object (
    [request] => VanGestelJasper\Router\Request Object (
        [payload] => VanGestelJasper\Router\Payload Object (
            [slug] => test
            [title] => PHP
            [subtitle] => Router
        )
    )
)