zoukankan      html  css  js  c++  java
  • RESTFUL接口学习之Phalcon版

    最近在看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

  • 相关阅读:
    Luogu3952 NOIP2017D1T2 时间复杂度
    Luogu4933 大师
    Luogu1966 火柴排队
    Luogu2881 排名的牛Ranking the Cows
    Luogu1439 最长公共子序列(LCS)
    Liferay7 BPM门户开发之20: 理解Asset Framework
    提高Liferay7的启动和运行速度
    liferay中jsonws的认证方法
    让Liferay的Service Builder连接其他数据库
    Liferay表结构介绍(四):Portlet相关表
  • 原文地址:https://www.cnblogs.com/hugmyloneliness/p/3630493.html
Copyright © 2011-2022 走看看