W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗(yàn)值獎勵
此擴(kuò)展基于 FastRoute 實(shí)現(xiàn),需要 PHP 5.4.0 及以上版本,可以通過配置實(shí)現(xiàn)自定義路由配置,從而輕松映射到PhalApi中的service接口服務(wù)。
從 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
到此安裝完畢!接下是插件的配置。
我們需要在 ./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'),
),
),
如果是使用nginx的情況下,需要添加以下配置:
if (-f $request_filename) {
expires max;
break;
}
if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php/$1 last;
}
然后重啟nginx。
//$ 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();
在完成上面的配置后,我們就可以這樣進(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
當(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"
}
當(dāng)在./Config/app.php的文件里配置錯誤的路由時,會直接拋出FastRoute\BadRouteException異常,以及時提示開發(fā)人員修正。
我們也可以實(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());
請訪問 FastRoute ,查看其官方說明。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: