php的單文件路由

inhere/sroute 很是輕量級的單一文件的路由器。簡潔、自定義性強php

referrer the project noahbuschermacaw , but add some feature.git

  • 支持請求方法: GET POST PUT DELETE HEAD OPTIONSgithub

  • 支持事件: found notFound. 你能夠作一些事情當觸發事件時(好比記錄日誌等)json

  • 支持設置匹配路由的解析器: SRoute::setMatchedRouteParser(). 你能夠自定義如何調用匹配的路由處理程序.bash

  • 支持自動匹配路由到控制器就像 yii 同樣, 請參看配置項 autoRoute.服務器

  • 支持手動調度一個路由經過方法 SRoute::dispatchTo()閉包

  • 你也能夠不配置任何東西, 它也能很好的工做app

安裝

{
    "require": {
        "inhere/sroute": "dev-master"
    }
}

使用

首先, 導入類框架

use inhere\sroute\SRoute;

添加路由

// 匹配 GET 請求. 處理器是個閉包 Closure
SRoute::get('/', function() {
    echo 'hello';
});

// 匹配參數 'test/john'
SRoute::get('/test/(\w+)', function($arg) {
    echo $arg; // 'john'
});

// 匹配 POST 請求
SRoute::post('/user/login', function() {
    var_dump($_POST);
});

// 匹配 GET 或者 POST
SRoute::map(['get', 'post'], '/user/login', function() {
    var_dump($_GET, $_POST);
});

// 容許任何請求方法
SRoute::any('/home', function() {
    echo 'hello, you request page is /home';
});

若是配置了 'ignoreLastSep' => true, '/index' 等同於 '/index/'yii

使用控制器方法

SRoute::get('/index', 'app\controllers\Home@index');

動態匹配控制器方法

動態匹配控制器方法, 需配置 'dynamicAction' => true

NOTICE: 使用動態匹配控制器方法, 應當使用 any() 添加路由. 即此時沒法限定請求方法 REQUEST_METHOD

// 訪問 '/home/test' 將會執行 'app\controllers\Home::test()'
SRoute::any('/home/(\w+)', app\controllers\Home::class);

// 可匹配 '/home', '/home/test' 等
SRoute::any('/home(/\w+)?', app\controllers\Home::class);

上面兩個的區別是 第一個沒法匹配 /home

使用方法執行器

配置 actionExecutor 爲你須要的方法名,例如配置爲 'actionExecutor' => 'run',那全部的方法請求都會提交給此方法。
會將真實的action名做爲參數傳入run($action), 須要你在此方法中調度來執行真正的請求方法。

在你須要將路由器整合到本身的框架時頗有用

示例:

// 訪問 '/user', 將會調用 app\controllers\User::run('')
SRoute::get('/user', 'app\controllers\User');

// 訪問 '/user/profile', 將會調用 app\controllers\User::run('profile')
SRoute::get('/user/profile', 'app\controllers\User');

// 同時配置 'actionExecutor' => 'run' 和 'dynamicAction' => true,
// 訪問 '/user', will call app\controllers\User::run('')
// 訪問 '/user/profile', will call app\controllers\User::run('profile')
SRoute::get('/user(/\w+)?', 'app\controllers\User');

自動匹配路由到控制器

支持自動匹配路由到控制器就像 yii 同樣, 需配置 autoRoute.

'autoRoute' => [
        'enable' => 1, // 啓用
        'controllerNamespace' => 'examples\\controllers', // 控制器類所在命名空間
        'controllerSuffix' => 'Controller', // 控制器類後綴
    ],

匹配全部

配置 'matchAll' 可用於攔截全部請求。 (例如網站維護時)

可容許配置 'matchAll' 的值爲

  • 路由path

'matchAll' => '/about', // a route path

將會直接執行此路由。

  • 回調

'matchAll' => function () {
        echo 'System Maintaining ... ...';
    },

將會直接執行此回調

設置事件處理(if you need)

SRoute::any('/404', function() {
    echo "Sorry,This page {$_GET['path']} not found.";
});
// 成功匹配路由
SRoute::on(SRoute::FOUND, function ($uri, $cb) use ($app) {
    $app->logger->debug("Matched uri path: $uri, setting callback is: " . is_string($cb) ? $cb : get_class($cb));
});

// 當匹配失敗, 重定向到 '/404'
SRoute::on('notFound', '/404');

// 或者, 當匹配失敗, 輸出消息...
SRoute::on('notFound', function ($uri) {
    echo "the page $uri not found!";
});

設置配置(if you need)

// set config
SRoute::config([
    'stopOnMatch' => true,
    'ignoreLastSep' => true,
    'dynamicAction' => true,
    
//    'matchAll' => '/', // a route path
//    'matchAll' => function () {
//        echo 'System Maintaining ... ...';
//    },
    
    // enable autoRoute, work like yii framework
    // you can access '/demo' '/admin/user/info', Don't need to configure any route
    'autoRoute' => [
        'enable' => 1,
        'controllerNamespace' => 'examples\\controllers',
        'controllerSuffix' => 'Controller',
    ],
]);
  • 默認配置以下

// 全部的默認的配置
[
    // stop on matched. only match one
    'stopOnMatch' => true,
    // Filter the `/favicon.ico` request.
    'filterFavicon' => false,
    // ignore last '/' char. If is True, will clear last '/', so '/home' equals to '/home/'
    'ignoreLastSep' => false,

    // match all request.
    // 1. If is a valid URI path, will match all request uri to the path.
    // 2. If is a callable, will match all request then call it
    'matchAll' => '', // eg: '/site/maintenance' or `function () { echo 'System Maintaining ... ...'; }`

    // auto route match @like yii framework
    'autoRoute' => [
        // If is True, will auto find the handler controller file.
        'enable' => false,
        // The default controllers namespace, is valid when `'enable' = true`
        'controllerNamespace' => '', // eg: 'app\\controllers'
        // controller suffix, is valid when `'enable' = true`
        'controllerSuffix' => '',    // eg: 'Controller'
    ],

    // default action method name
    'defaultAction' => 'index',

    // enable dynamic action.
    // e.g
    // if set True;
    //  SRoute::any('/demo/(\w+)', app\controllers\Demo::class);
    //  you access '/demo/test' will call 'app\controllers\Demo::test()'
    'dynamicAction' => false,

    // action executor. will auto call controller's executor method to run all action.
    // e.g
    //  `run($action)`
    //  SRoute::any('/demo/(:act)', app\controllers\Demo::class);
    //  you access `/demo/test` will call `app\controllers\Demo::run('test')`
    'actionExecutor' => '', // 'run'
]

NOTICE: 必須在調用 SRoute::dispatch() 以前使用 SRoute::config() 來進行一些配置

開始路由分發

SRoute::dispatch();

運行示例

你能夠經過 bash ./php_server 來運行一個測試服務器, 如今你能夠訪問 http://127.0.0.1:5670

項目地址

相關文章
相關標籤/搜索