infotechnohelp/cakephp-json-api_advanced

CakePHP 3 插件

安装: 381

依赖: 2

建议者: 0

安全: 0

星星: 0

分支: 0

类型:cakephp-plugin

dev-master 2019-07-28 07:50 UTC

This package is auto-updated.

Last update: 2024-09-28 19:42:13 UTC


README

实现

composer require infotechnohelp/cakephp-json-api_advanced

1. 添加插件

src/Application.php → bootstrap()

$this->addPlugin('Infotechnohelp/JsonApi', ['routes' => true]);

或者使用终端

bin/cake plugin load Infotechnohelp/JsonApi -r

2. 设置路径前缀

config/infotechnohelp.json-api.yml

pathPrefixes:
- api
- auth-api (automatically later)

如果路由包含 /api/ 字符串 ('/' 从两边),则请求被视为 API 请求。

可以添加任何所需的路径前缀。

3. 设置 ErrorHandlerMiddleware(JSON 响应结构)

APP/src/Application.php 中手动替换

use Cake\Error\Middleware\ErrorHandlerMiddleware;use Infotechnohelp\JsonApi\Middleware\ErrorHandlerMiddleware;

用法

API 层

创建 Api 控制器

路径: APP/src/Controller/Api

namespace App\Controller\Api;

use Infotechnohelp\JsonApi\Traits\ApiController;


class MyController extends AppContoller
{
    use ApiController;
    
    public function get()
    {
        $this->getRequest()->getQuery(); // GET data params
        $this->_setResponse([1, 2, 3]);
    }
	
	public function post()
    {
        $this->_getRequestData(); // POST data params
        $this->_setResponse([1, 2, 3]);
    }
}

响应结构

{ "data": {"1", "2", "3"}, "code": 200, message": null }

如果消息有值(异常消息),则数据为 null。

如果数据为 null,但没有抛出异常,则会抛出自定义异常 'Data was not set'。

发送请求

前缀 api/

要发送请求到 APP/src/Controller/Api/MyController→get(),使用此路径

api/my/get

如果您需要在请求体中传递像 nulltruefalse 这样的值,您需要将 JS 数据对象转换为 JSON。API 层将自动解析请求数据。

例如

        // Values will be parsed as strings
        api.postJson("demo/create", {
            _true: true,
            _false: false,
            _null: null
        }, function (response) {
            log.single(response);
        });

        // Values will be parsed as booleans and NULL
        api.postJson("demo/create", JSON.stringify({
            _true: true,
            _false: false,
            _null: null
        }), function (response) {
            log.single(response);
        });

允许的动作-方法对

index, view, read, get → GET

create, add, post → POST

update → POST, PUT

delete → POST, DELETE