基于FastRoute的快速路由(支持RESTful)

2018-11-21 21:32 更新

3.11.1 擴(kuò)展類庫:基于FastRoute的快速路由

此擴(kuò)展基于 FastRoute 實(shí)現(xiàn),需要 PHP 5.4.0 及以上版本,可以通過配置實(shí)現(xiàn)自定義路由配置,從而輕松映射到PhalApi中的service接口服務(wù)。

3.11.2 安裝和配置

(1)擴(kuò)展包下載

 PhalApi-Library 擴(kuò)展庫中下載獲取 FastRoute 擴(kuò)展包,如使用:

git clone https://git.oschina.net/dogstar/PhalApi-Library.git

然后把 FastRoute 目錄復(fù)制到 ./PhalApi/Library/ 下,即:

cp ./PhalApi-Library/FastRoute/ ./PhalApi/Library/ -R

到此安裝完畢!接下是插件的配置。

(2)擴(kuò)展包配置

我們需要在 ./Config/app.php 配置文件中追加以下配置:

    /**
     * 擴(kuò)展類庫 - 快速路由配置
     */
    'FastRoute' => array(
         /**
          * 格式:array($method, $routePattern, $handler)
          *
          * @param string/array $method 允許的HTTP請求方式,可以為:GET/POST/HEAD/DELETE 等
          * @param string $routePattern 路由的正則表達(dá)式
          * @param string $handler 對應(yīng)PhalApi中接口服務(wù)名稱,即:?service=$handler
          */
        'routes' => array(
            array('GET', '/user/get_base_info/{user_id:\d+}', 'User.GetBaseInfo'),
            array('GET', '/user/get_multi_base_info/{user_ids:[0-9,]+}', 'User.GetMultiBaseInfo'),
        ),
    ),

(3)nginx的協(xié)助配置

如果是使用nginx的情況下,需要添加以下配置:

    if (-f $request_filename) {
        expires max;
        break;
    }

    if (!-e $request_filename) {
        rewrite ^/(.*)$ /index.php/$1 last;
    }

然后重啟nginx。

3.11.3 入門使用

(1)入口注冊

//$ vim ./Public/index.php

$loader->addDirs('Library');

// 其他代碼....

//顯式初始化,并調(diào)用分發(fā)
DI()->fastRoute = new FastRoute_Lite();
DI()->fastRoute->dispatch();

/** ---------------- 響應(yīng)接口請求 ---------------- **/

$api = new PhalApi();
$rs = $api->response();
$rs->output();

3.11.3 調(diào)用效果及擴(kuò)展

(1)通過新的路由正常訪問

在完成上面的配置后,我們就可以這樣進(jìn)行頁面訪問測試:

  http://library.phalapi.com/user/get_base_info/1
  等效于:http://library.phalapi.com/?service=User.GetBaseInfo&user_id=1

  http://library.phalapi.com/user/get_multi_base_info/1,2
  等效于:http://library.phalapi.com/?service=User.GetMultiBaseInfo&user_ids=1,2

(2)非法訪問

當(dāng)請求的HTTP方法與配置的不符合時,就會返回405錯誤,如我們配置了:

array('POST', '/user/{id:\d+}/{name}', 'handler2'),

但是通過GET方式來訪問,即:

http://library.phalapi.com/user/123/name

則會返回:

{
    "ret": 405,
    "data": [],
    "msg": "快速路由的HTTP請求方法錯誤,應(yīng)該為:POST"
}

(3)路由配置錯誤

當(dāng)在./Config/app.php的文件里配置錯誤的路由時,會直接拋出FastRoute\BadRouteException異常,以及時提示開發(fā)人員修正。

(4)異常錯誤處理器

我們也可以實(shí)現(xiàn)FastRoute_Handler接口來自定義我們自己的錯誤異常處理回調(diào)函數(shù)。如:

class FastRoute_Handler_App implements FastRoute_Handler {

    public function excute(PhalApi_Response $response) {
        // ... ...
    }
}

然后,在分發(fā)時指定handler:

DI()->fastRoute->dispatch(new FastRoute_Handler_App());

3.11.4 更多路由配置說明

請訪問 FastRoute ,查看其官方說明。

以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號