isholao/router

PHP 请求路由

1.0.1 2017-11-21 18:43 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:08:38 UTC


README

Build Status

安装

使用 composer 安装

composer require isholao/router

需要 PHP 7.1 或更高版本。

使用方法

以下是一个基本的使用示例

<?php

require '/path/to/vendor/autoload.php';

$c = \Isholao\Router\RouteCollection();
$c->get('/','get_all_users_responder');
$c->mapMany('GET|POST','/login','login_responder','login');
$c->disptach('GET','/login'); //return Route instance or null

定义路由

$c = \Isholao\Router\RouteCollection();
$c->mapOne('GET', '/login', 'defined_responder');
$c->mapOne('GET', '/{lang=(?:en|de)}/login', 'defined_responder');
or
$c->mapMany('GET|POST', '/login, 'defined_responder');

您还可以通过在定义的段之后添加一个 ? 来创建一个可选的路径段。

$c = \Isholao\Router\RouteCollection();
$c->mapOne('GET', '/something/{hash=[a-zA-Z]+}?', 'defined_responder');
or
$c->mapMany('GET|POST', '/login, 'defined_responder');

您可以为段设置一个默认值,因为每个定义的路由都返回一个 \Router\Route 实例。注意,这只能在 mapOne 方法或任何辅助函数 get(), post(), head(), delete(), option(), put() 上完成

$c = \Isholao\Router\RouteCollection();
$c->mapOne('GET', '/something/{hash=[a-zA-Z]+}', 'defined_responder')->setParam('hash','asd8asdasd9');
or
$c->delete('/something/{hash=[a-zA-Z]+}', 'defined_responder')->setParam('hash','asd8asdasd9');

路由分组

此外,您还可以在组内部指定路由。组内部定义的所有路由都将具有一个共同的前缀。

例如,将路由定义为

$c = \Isholao\Router\RouteCollection();
$c->groupRoutes('/admin', function (\Isholao\Router\RouteCollectionInterface $r) {
    $r->mapOne('GET', '/do-something', 'handler'); // this becomes `/admin/do-something`
    $r->post('/do-something-else', function(){}); //  // this becomes `/admin/do-another-thing`
});

分发 URI

通过调用创建的 \Isholao\Router\RouteCollection 对象的 dispatch() 方法来分发 URI。此方法接受 HTTP 方法和一个 URI。

$c = \Isholao\Router\RouteCollection();
$c->groupRoutes('/admin', function (\Isholao\Router\RouteCollectionInterface $r) {
    $r->mapOne('GET', '/do-something', 'handler'); // this becomes `/admin/do-something`
    $r->post('/do-something-else', function(){}); //  // this becomes `/admin/do-another-thing`
});

$c->dispatch('GET','/admin/do-something'); // return a \Isholao\Router\Route instance or null