最近在看Facebook的接口,发现都是RESTFUL格式的,
于是我也想学习RESTFUL的写法,正好Phalcon上有个样例,原地址:http://docs.phalconphp.com/en/latest/reference/tutorial-rest.html
现在用Phalcon框架做一个简单的RESTFUL服务,接口如下:
Method | Url | Action |
GET | /api/robots | 获得所有的robots |
GET | /api/robots/search/{name} | 按名称来搜索 |
GET | /api/robots/{id} | 按ID来搜索 |
POST | /api/robots | 创建新的robot |
PUT | /api/robots/{id} | 更新已有的robot |
DELETE | /api/robots/{id} | 删除已有的robot |
用Phalcon来实现很容易,如实现查询接口
$app->get('/api/robots', function() { $robots = Robots::find(); echo json_encode($robots->toArray()); });
实现新建数据接口
1 $app->post('/api/robots/', function() use ($app) { 2 $robot = new Robots; 3 $robot->name = $app->request->getPost('name'); 4 $robot->type = $app->request->getPost('type'); 5 $robot->year = $app->request->getPost('year'); 6 7 $response = new Phalcon\Http\Response(); 8 if ($robot->save() == true) { 9 $response->setStatusCode(201, 'Created'); 10 $robot->id = $robot->id; 11 $response->setJsonContent(array('status' => 'OK', 'data' => $robot->toArray())); 12 } else { 13 getErrors($response, $robot); 14 } 15 return $response; 16 }; 17 18 function getErrors($response, $robot) 19 { 20 $response->setStatusCode(409, "Conflict"); 21 $errors = array(); 22 foreach ($model->getMessages() as $message) { 23 $errors[] = $message->getMessage(); 24 } 25 26 $response->setJsonContent(array('status' => 'ERROR', 'message' => $errors)); 27 }
更新数据
1 $app->put('/api/robots/{id:[0-9]+}', function($id) use($app) { 2 $robot = Robots::findFirst(array( 3 "id = ?0", 4 "bind" => array($id) 5 )); 6 7 $response = new Phalcon\Http\Response(); 8 if (!$robot) { 9 $response->setJsonContent(array('status' => 'NOT-FOUND')); 10 } else { 11 $robot->name = $app->request->getPut('name'); 12 $robot->type = $app->request->getPut('type'); 13 $robot->year = $app->request->getPut('year'); 14 if ($robot->save()) { 15 $response->setJsonContent(array('status' => 'OK')); 16 } else { 17 getErrors($response, $robot); 18 } 19 } 20 return $response; 21 });
等等。
完整的代码在github上面,请戳-->https://github.com/CrusePeng/rest/tree/master