thinkphp不開啟路由,php 快速路由,基于FastRoute的快速路由(支持RESTful)

 2023-12-12 阅读 27 评论 0

摘要:3.11.1 擴展類庫:基于FastRoute的快速路由thinkphp不開啟路由、此擴展基于FastRoute實現,需要PHP 5.4.0及以上版本,可以通過配置實現自定義路由配置,從而輕松映射到PhalApi中的service接口服務。3.11.2 安裝和配置rocketmq php。(1)擴展包下載從P

3.11.1 擴展類庫:基于FastRoute的快速路由

thinkphp不開啟路由、此擴展基于FastRoute實現,需要PHP 5.4.0及以上版本,可以通過配置實現自定義路由配置,從而輕松映射到PhalApi中的service接口服務。

3.11.2 安裝和配置

rocketmq php。(1)擴展包下載

從PhalApi-Library擴展庫中下載獲取FastRoute擴展包,如使用:

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

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

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

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

(2)擴展包配置

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

/** * 擴展類庫 - 快速路由配置 */ 'FastRoute' => array( /** * 格式:array($method, $routePattern, $handler) * *@paramstring/array $method 允許的HTTP請求方式,可以為:GET/POST/HEAD/DELETE 等 *@paramstring $routePattern 路由的正則表達式 *@paramstring $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'), ), ),

(3)nginx的協助配置

如果是使用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()->fastRoute = new FastRoute_Lite(); DI()->fastRoute->dispatch(); /** ---------------- 響應接口請求 ---------------- **/ $api = new PhalApi(); $rs = $api->response(); $rs->output();

3.11.3 調用效果及擴展

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

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

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)非法訪問

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

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

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

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

則會返回:

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

(3)路由配置錯誤

當在./Config/app.php的文件里配置錯誤的路由時,會直接拋出FastRouteBadRouteException異常,以及時提示開發人員修正。

(4)異常錯誤處理器

我們也可以實現FastRoute_Handler接口來自定義我們自己的錯誤異常處理回調函數。如:

classFastRoute_Handler_AppimplementsFastRoute_Handler{ public functionexcute(PhalApi_Response $response){ // ... ... } }

然后,在分發時指定handler:

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

3.11.4 更多路由配置說明

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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/5/194474.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息