infotechnohelp / cakephp-json-api_advanced
CakePHP 3 插件
Requires
- cakephp/cakephp: ^3.7
- symfony/yaml: ^4.2
- vlucas/phpdotenv: ^2.4
Requires (Dev)
- doctrine/instantiator: 1.0.*
- phpunit/phpunit: ^5.7|^6.0
- squizlabs/php_codesniffer: ^3.2
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
如果您需要在请求体中传递像 null
、true
或 false
这样的值,您需要将 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