php 使用 restler 框架构建 restfull api
php 使用 restler 框架构建 restfull api
restler 轻量级,小巧,构建restfull api非常方便!
官网:http://restler3.luracast.com/
目前最后的是3.0版本,我测试使用的是2.2版本;
一:安装restler2
1. 下载 https://github.com/Luracast/Restler/tree/2.2.0
2. exmple目录下放的是例子
3. 把restler 目录的所有文件放到你的web服务下;
二:开始创建restfull api
1. index.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php //引入restler库 require_once './restler/restler.php' ; $r = new Restler(); //配置支持的返回数据格式,json,xml等 $r ->setSupportedFormats( 'JsonFormat' ); //接口列表文件 $r ->addAPIClass( 'api' ); $r ->handle(); ?> |
2. 主接口文件 api.php, 上述1中的api表示的类名api
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | <?php //工具类 include 'util.php' ; class api { //get 请求 /url/xml public function getXml( $deviceType ) { if (! $deviceType ) { return array ( 'xml' => "error " ); } if ( $deviceType == '1' ) { //return ios return array ( 'xml' => "ios" ); } elseif ( $deviceType == '2' ) { //return android return array ( 'xml' => "android" ); } elseif ( $deviceType == '3' ) { //return pc return array ( 'xml' => "pc" ); } else { return array ( 'xml' => "none support deviceType" ); } } //post 请求, public function postXXL( $dev ) { return returnXML( $dev ); } //当类名与文件名相同时,可以不用 include 该类 public function getAAA() { $bd = new Baidu(); return $ret = array ( 'site' => "baidu.com" , );; } } ?> |
三:访问测试
1. api.php中所有public的方法,就是请求的方法,get或post 以方法名的前关键字为准;
如getXml方法,测试请求方式为
get http://127.0.0.1/tp/api/xml.josn
或 http://127.0.0.1/tp/api/xml/1.json
或http://127.0.0.1/tp/api/xml?deviceType=1
后面的1对应getXml的请求字段 $deviceType
2. 其他函数同上
3. 如果要同时支持xml
如http://127.0.0.1/tp/api/xml/1.xml
http://127.0.0.1/tp/api/xml/1.json
在index.php配置
$r->setSupportedFormats('JsonFormat', 'XmlFormat');
更多:http://restler3.luracast.com/examples/index.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具