mind2minds/cakephp-rest-api

CakePHP 3 插件,用于构建 REST API 服务

1.0.2 2018-06-19 12:31 UTC

This package is not auto-updated.

Last update: 2024-09-19 18:23:30 UTC


README

此插件用于创建 REST API 端点。

需求

此插件有以下需求

  • CakePHP 3.0.0 或更高版本。
  • PHP 5.4.16 或更高版本。

安装

您可以使用 composer 将此插件安装到您的 CakePHP 应用程序中。

安装 composer 包的推荐方法是

composer require mind2minds/cakephp-rest-api

安装后,加载插件

Plugin::load('RestApi', ['bootstrap' => true]);

或者,您可以使用 shell 命令加载插件

$ bin/cake plugin load -b RestApi

用法

您只需要创建与 API 相关的控制器,并将其扩展到 RestApi\Controller\AppController 而不是默认的 AppController

namespace App\Controller;

use RestApi\Controller\AppController;

/**
 * Demo Controller
 */
class DemoController extends AppController
{

    /**
     * Read contacts or single contact details when id given
     */
    public function contacts($id = null)
    {
        $contacts = [
            //...
        ];
        $result = [];
        if(!empty($id)) {
            if (empty($contacts[$id])) {
                $this->_error(404, 'Missing Contacts', 'Invalid Id Supplied');
            } else {
                $contact = $contacts[$id];
                $result = [
                    'Id' => $id,
                    'type' => 'Contact',
                    '_name' => $contact['name'],
                    '_email' => $contact['email']
                ];
            }
        } else {
            foreach ($contacts as $id => $contact) {
                $result[] = [
                    'Id' => $id,
                    'type' => 'Contact',
                    '_name' => $contact['name'],
                    '_email' => $contact['email']
                ];
            }
        }
        $this->_createJsonApiResponse($result);
    }
}

您可以在动作函数中定义您的逻辑。对于上述示例,您将以 json 格式获得以下响应(根据 jsonapi 规范的 json 响应),

{
  "data": {
    "type": "contacts",
    "id": "1",
    "attributes": {
      // ... this contact's attributes
    },
    "relationships": {
      // ... this contact's relationships if any
    }
  }
}

上述示例的 URL 将是 http://yourdomain.com/api/contacts。您可以通过在 APP/config/routes.php 中设置路由来自定义它。/api/contacts 端点示例是

$routes->connect('/api/contacts', ['plugin' => 'RestApi', 'controller' => 'Demo', 'action' => 'contacts']);

接受基本 HTTP 身份验证头,例如 Basic NzQxZjNhOTctZTBjNC00OTFjLWI3MDItY2JlYTA5NzVmODhl,这是默认演示 API 密钥

使用简单:)

报告问题

如果您对此插件有任何问题或任何错误,请在 GitHub 上提交问题。