mixerapi / cakephp-rest
CakePHP bake 控制台的缺失 RESTful API 组件。几秒钟内创建 RESTful API 框架。
Requires
- php: ^8.0
- cakephp/cakephp: ^4.2
- nikic/php-parser: ^4.8
- thecodingmachine/class-explorer: ^1.1
This package is auto-updated.
Last update: 2024-09-26 01:00:05 UTC
README
此插件通过为您创建路由来快速启动 API 项目。
- 通过单个命令构建您的
routes.php
文件或使用便捷的 AutoRouter 自动公开 RESTful CRUD 路由。 - 为 CRUD 操作设置默认 HTTP 状态码
此插件假定您已经创建了模型和控制器。有关后者的帮助,请查看 MixerApi/Bake。有关本插件未涵盖的复杂路由场景,请参阅官方 RESTful 路由 文档。
更多信息请访问 MixerAPI.com。
安装
!!! info "" 如果已安装 MixerAPI,您可以跳过此步骤。
composer require mixerapi/rest bin/cake plugin load MixerApi/Rest
或者,在 composer 安装后,您可以手动在您的应用程序中加载此插件
# src/Application.php public function bootstrap(): void { // other logic... $this->addPlugin('MixerApi/Rest'); }
AutoRouter
创建路由已经很简单,但 AutoRouter 使得构建 CRUD 路由变得轻而易举。如果您刚开始使用 CakePHP 构建API,这将非常棒。
在您的 routes.php
中,只需添加 \MixerApi\Rest\Lib\AutoRouter
# config/routes.php $routes->scope('/', function (RouteBuilder $builder) { // ... other routes (new AutoRouter($builder))->buildResources(); // ... other routes });
这将添加 CRUD 控制器操作的路由(索引、添加、编辑、查看和删除)。如果您的控制器没有 CRUD 方法,则将跳过该路由。AutoRouting 也适用于插件。
# in your plugins/{PluginName}/routes.php file (new AutoRouter($builder, new ResourceScanner('MyPlugin\Controller')))->buildResources();
创建路由
虽然 AutoRouter 使得生活变得轻松,但它必须扫描您的控制器来构建 RESTful 资源,这会略有性能损失。别担心,您可以使用 mixerapi:rest route create
来为您编写路由。这将直接将路由写入您的 routes.php 文件。
# writes to `config/routes.php` bin/cake mixerapi:rest route create
使用 --prefix
指定前缀
bin/cake mixerapi:rest route create --prefix /api
对于插件使用 --plugin
# writes to `plugins/MyPlugin/config/routes.php` bin/cake mixerapi:rest route create --plugin MyPlugin
要执行 dry-run,请使用 --display
选项
bin/cake mixerapi:rest route create --display
有关非 CRUD 路由、子资源和高级路由,请参阅 CakePHP RESTful 路由 文档
列出路由
此功能类似于 bin/cake routes
,但仅显示 RESTful 路由并改进了一些信息格式。
bin/cake mixerapi:rest route list
要限制输出到特定插件,请使用 --plugin
选项
# limit to a plugin: bin/cake mixerapi:rest route list --plugin MyPlugin #limit to main application: bin/cake mixerapi:rest route list --plugin App
CRUD HTTP 状态码
默认状态码为
要更改这些,请加载 MixerApi.Rest.crud.statusCodes
配置
return [ 'MixerApi' => [ 'Rest' => [ 'crud' => [ 'statusCodes' => [ 'index' => 200, 'view' => 200, 'add' => 201, 'edit' => 200, 'delete' => 204 ] ] ] ] ];
请参阅 CakePHP 关于 加载配置文件 的文档