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

  • 相关阅读:
    centos7下部署nginx+supervisor+netcore2.1服务器环境
    centos6.1配置nodejs运行环境
    centos下远程访问redis端口配置
    如何成为一名合格的软件测试师
    Maven之安装及构建简单项目 掠影
    JAVA语言单元测试框架——JUnit浅析
    软件测试 之 白盒测试 掠影
    软件测试 之 黑盒测试 掠影
    以一个闰年检测程序为例的非法字符异常输入检测
    学习心得——测试框架浅析
  • 原文地址:https://www.cnblogs.com/hugmyloneliness/p/3630493.html
Copyright © 2011-2022 走看看