此扩展基于 实现,须要 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());
请访问 ,查看其官方说明。