Restful API现在非常的流行啊,目前工作的项目也使用了ASP.NET Web API技术。用下来的感觉是前台数据的展现层可以和后台数据的处理层解耦性很好。所以在开发阶段,前台数据展现页面布局和后台数据处理调整起来都很方便。Restful API利用了http协议,配合一些类似backbone这样的js mvc框架非常好用。
最近有一个需求是用php实现一个简单的 Restful WebAPI。因为之前用的ASP.NET Web API,所以就模拟实现一下它的结构。
由路由Router来选择Controller,由method选择Action,数据传输使用json。举个例子
Get /api/resouces 返回资源信息 Controller:Resouces Action: get()
Get /api/resouces/{id} 返回资源信息 Controller:Resouces Action: get($id)
Post /api/resouces 创建资源信息 Controller:Resouces Action: post()
Put /api/resouces/{id} 更新资源信息 Controller:Resouces Action: get($id)
Delete /api/resouces/{id} 删除资源信息 Controller:Resouces Action: delete($id)
总结看来,对于url我们只需要处理2种:/api/resouces 和 /api/resouces/2。
下面的文章从路由开始的记录一个restful api 的简单实现。
(做个说明,由于本人php编程经验有限,希望大家对文章中出现的任何问题都不吝赐教,可以共同进步)