sw04/route-me

具有路由分组和前后操作的router

v1 2014-11-18 09:25 UTC

This package is not auto-updated.

Last update: 2024-09-24 03:17:51 UTC


README

轻量级php路由库支持

  • 路由
  • 可选和需求参数
  • 分组路由
  • 路由前后操作
  • 定义控制器、方法和参数

Composer安装

composer require sw04/route-me

初始化

$router = \Router\Singleton::getInstance();

支持GET和POST方法,需要整数和字符串参数的简单路由

$router->get('/show/{[0-9]+}'); //sample: GET /show/1024
$router->post('/show/{[a-z]+}'); //sample: POST /show/sample

不需要参数的简单路由

$router->get('/show/!{[0-9]+}'); //sample: GET /show or /show/1024

定义控制器和方法的简单路由

$router
    ->setController('index')
    ->setMethod('index')
    ->get('/')
    ->clear();

简单分组路由(设置前缀"/admin")并添加路由匹配前的操作

function isAuth() {
    //check auth & return true or false
    return true;
}
function isAdmin() {
    //check role is admin or not & return true or false
    return false;
}
$router
    ->setPrefix('/admin')
    ->setAction('before', 'isAuth')
    ->setAction('before', 'isAdmin')
    ->get('/dashboard')
    ->clear();

为所有类简单设置前缀(命名空间)

$router->setNamespace('\\Application\\Project\\');

匹配路由

try {
    $result = $router->match(getenv('REQUEST_URI'));
    if (is_array($result)) { //convert to json if is array
        $result = json_encode($result);
    }
    echo $result; //echo result of match
} catch(\Router\RouterException $e) {
    echo $e->getMessage().' code is '.$e->getCode();
}

所有路由设置路由的后续要求

method - GET, POST, ANY
prefix - for route url
url - to route
actions - before & after route match
defineClass - define controller
defineMethod - define method
defineParams - define params

为了清除所有这些要求,请使用

$routes->clear();