此擴展基於 實現,須要 PHP 5.4.0 及以上版本,能夠經過配置實現自定義路由配置,從而輕鬆映射到PhalApi中的service接口服務。php
從 PhalApi-Library 擴展庫中下載獲取 FastRoute 七牛擴展包,如使用:nginx
git clone https://git.oschina.net/dogstar/PhalApi-Library.git
而後把 FastRoute 目錄複製到 ./PhalApi/Library/ 下,即:git
cp ./PhalApi-Library/FastRoute/ ./PhalApi/Library/ -R
處處安裝完畢!接下是插件的配置。正則表達式
咱們須要在 ./Config/app.php 配置文件中追加如下配置:vim
/** * 擴展類庫 - 快速路由配置 */ 'FastRoute' => array( /** * 格式:array($method, $routePattern, $handler) * * @param string/array $method 容許的HTTP請求方烤雞,能夠爲:GET/POST/HEAD/DELETE 等 * @param string $routePattern 路由的正則表達式 * @param string $handler 對應PhalApi中接口服務名稱,即:?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'), ), ),
若是是使用nginx的狀況下,須要添加如下配置:api
if (-f $request_filename) { expires max; break; } if (!-e $request_filename) { rewrite ^/(.*)$ /index.php/$1 last; }
而後重啓nginx。app
//$ vim ./Public/index.php$loader->addDirs('Library');// 其餘代碼....//顯式初始化,並調用分發DI()->fastRoute = new FastRoute_Lite();DI()->fastRoute->dispatche();/** ---------------- 響應接口請求 ---------------- **/$api = new PhalApi();$rs = $api->response();$rs->output();
在完成上面的配置後,咱們就能夠這樣進行頁面訪問測試:函數
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
當請求的HTTP方法與配置的不符合時,就會返回405錯誤,如咱們配置了:測試
array('POST', '/user/{id:\d+}/{name}', 'handler2'),
可是經過GET方式來訪問,即:spa
http://library.phalapi.com/user/123/name
則會返回:
{ "ret": 405, "data": [], "msg": "快速路由的HTTP請求方法錯誤,應該爲:POST"}
當在./Config/app.php的文件裏配置錯誤的路由時,會直接拋出FastRoute\BadRouteException異常,以及時提示開發人員修正。
咱們也能夠實現FastRoute_Handler接口來自定義咱們本身的錯誤異常處理回調函數。如:
class FastRoute_Handler_App implements FastRoute_Handler { public function excute(PhalApi_Response $response) { // ... ... }}
而後,在分發時指定handler:
DI()->fastRoute->dispatche(new FastRoute_Handler_App());
請訪問 ,查看其官方說明。