快速学习-RestFul实战

三、RestFul实战

1、TP框架中的资源路由

手册-路由-资源路由、手册-控制器-资源控制器

①创建api模块

php think build --module api

②创建news控制器

php think make:controller api/News

③设置路由(application/route.php)

\think\Route::resource('news','api/news');

相当于分别设置了以下路由:

\think\Route::get('news','api/news/index');
\think\Route::get('news/create','api/news/create');
\think\Route::post('news','api/news/save');
\think\Route::get('news/:id','api/news/read');
\think\Route::get('news/:id/edit','api/news/edit');
\think\Route::put('news/:id','api/news/update');
\think\Route::delete('news/:id','api/news/delete');

设置后会自动注册7个路由规则,如下:

标识 请求类型 生成路由规则 对应操作方法(默认)
index GET news index
create GET news/create create
save POST news save
read GET news/:id read
edit GET news/:id/edit edit
update PUT news/:id update
delete DELETE news/:id delete

④修改News控制器,返回json格式数据

<?php

namespace app\api\controller;

use think\Controller;
use think\Request;

class News extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'index']);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'create']);
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'save']);
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'read']);
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function edit($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'edit']);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'update']);
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        return json(['code' => 200, 'msg' => 'success', 'data'=>'delete']);
    }
}

通过postman 分别访问以下七个地址:

请求方式	 请求地址
get			http://www.tpshop.com/news
get			http://www.tpshop.com/news/create
post		http://www.tpshop.com/news
get			http://www.tpshop.com/news/33
get			http://www.tpshop.com/news/33/edit
put			http://www.tpshop.com/news/33
delete		http://www.tpshop.com/news/33

2、ajax请求restful接口

public目录下,创建测试文件 api.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax请求restful接口</title>
    <script src="/static/admin/js/jquery-1.8.1.min.js"></script>
</head>
<body>
<input type="button" id="index" value="index">
<input type="button" id="create" value="create">
<input type="button" id="save" value="save">
<input type="button" id="read" value="read">
<input type="button" id="edit" value="edit">
<input type="button" id="update" value="update">
<input type="button" id="delete" value="delete">
<script>
    $(function(){
        $('#index').click(function(){
            $.ajax({
                "url":"/news",
                "type":"get",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#create').click(function(){
            $.ajax({
                "url":"/news/create",
                "type":"get",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#save').click(function(){
            $.ajax({
                "url":"/news",
                "type":"post",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#read').click(function(){
            $.ajax({
                "url":"/news/33",
                "type":"get",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#edit').click(function(){
            $.ajax({
                "url":"/news/33/edit",
                "type":"get",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#update').click(function(){
            $.ajax({
                "url":"/news/33",
                "type":"put",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#delete').click(function(){
            $.ajax({
                "url":"/news/33",
                "type":"delete",
                "data":"",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
    });
</script>
</body>
</html>

在这里插入图片描述

3、请求伪装

部分客户端(比如低版本浏览器)可能仅支持get请求、post请求,不支持delete请求和put请求。

TP框架提供了对“请求伪装”的支持,可以使用post请求携带_method参数,伪装成其他请求。

在这里插入图片描述

比如 使用ajax的post请求伪装put请求

public/api.html中 添加以下代码

<input type="button" id="post_to_put" value="伪装put">
<input type="button" id="post_to_delete" value="伪装delete">
<script>
    $(function(){
        $('#post_to_put').click(function(){
            $.ajax({
                "url":"/news/33",
                "type":"post",
                "data":"_method=put",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
        $('#post_to_delete').click(function(){
            $.ajax({
                "url":"/news/33",
                "type":"get",
                "data":"_method=delete",
                "dataType":"json",
                "success":function(res){
                    console.log(res);
                }
            });
        });
    })
</script>

4、Restful常用的资源路由

新增页面页面展示 create方法 和 修改页面页面展示 edit方法 一般可以不用。

标识 请求类型 生成路由规则 对应操作方法(默认) 备注
index GET news index 查询多条数据(列表)
read GET news/:id read 查询一条数据(详情、修改页面展示)
save POST news save 新增一条数据
update PUT news/:id update 修改一条数据
delete DELETE news/:id delete 删除一条数据

5、实际开发中的Restful

Restful接口通常返回的是完整的数据模型,粒度过于“粗”,对客户端不友好(客户端可能只需要其中一小部分字段)。

Restful典型使用场景:开放API(各种开放平台的数据api)。开放API之所以开放,就是因为不知道也不关心客户端需要什么返回结果,直接返回完整的数据,好处是通用。

实际开发中,通常都是内部接口开发,需求非常明确,所以一般都是灵活借鉴Restful中的优点,结合自己的实际情况,来设计自己的内部api,在基本的增删改查接口之外,通常会设计一些业务接口(根据业务逻辑需要,一个接口中对多个资源的数据进行整合再返回)。

发布了1842 篇原创文章 · 获赞 1964 · 访问量 17万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/105122247
今日推荐