berrygoudswaard/cakephp-api

安装次数: 1,797

依赖者: 0

建议者: 0

安全性: 0

星标: 0

关注者: 3

分支: 0

公开问题: 0

类型:cakephp-plugin

4.2.0 2021-10-13 14:24 UTC

This package is not auto-updated.

Last update: 2024-09-12 04:22:18 UTC


README

此插件包含一个组件,使使用 CakePHP 创建 API 输出变得更加容易

需求

  • CakePHP 3.1+

安装

composer require berrygoudswaard/cakephp-api

用法

在你的应用的 config/bootstrap.php 文件中添加

Plugin::load('BerryGoudswaard/Api');

然后在你的控制器中添加以下代码来加载组件

$this->loadComponent('BerryGoudswaard/Api.Api', [
    'cors' => [
        'allowHeaders' => ['Content-Type', 'Authorization'],
        'allowMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
        'allowOrigins' => ['https://:4200', 'http://www.berrygoudswaard.nl'],
        'allowCredentials' => 'true',
    ]
]);

输出数据

public function index()
{
    $tags = $this->Tags->find();

    $this->Api->addData('tags', $tags);
    return $this->Api->output();
}

上面的代码将输出类似以下的内容

{
    "message": "OK",
    "code": 200,
    "data": {
        "tags": {
            "items": [
                {
                    "id": 1,
                    "tag": "cakephp"
                }, {
                    "id": 2,
                    "tag": "plugin"
                }
            ]
        }
    }
}