Yii2 Restful API - 添加新操作的示例 [英] Yii2 Restful API - Example to Add a New Action

查看:33
本文介绍了Yii2 Restful API - 添加新操作的示例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于使用 Yii2 构建 Restful API,有没有人有关于如何在控制器中添加新操作的好例子?谢谢.

For buiding restful API using Yii2, does anyone has good example on how to add a new action in a controller? Thanks.

推荐答案

我不确定您是要求 CRUD 之外的额外操作还是仅针对 CRUD,所以我针对这两种情况写了详细信息.

I am not sure if you are asking for extra actions beside CRUD or just for CRUD, so I write in details for both cases.

首先,框架包含\yii\rest\ActiveController,提供典型的restful API操作和URL管理.

Firstly, the framework includes \yii\rest\ActiveController that provides typical restful API operation and URL management.

基本上,控制器预定义 CRUD 操作如下:

Basically, the controller predefines the CRUD operations as followed:

POST/resource -> actionCreate -> 创建资源

POST /resource -> actionCreate -> Create the resource

GET/resource/{id} -> actionView -> 读取资源

GET /resource/{id} -> actionView -> Read the resource

PUT, PATCH/resource/{id} -> actionUpdate -> 更新资源

PUT, PATCH /resource/{id} -> actionUpdate -> Update the resource

DELETE/resource/{id} -> actionDelete -> 删除资源

DELETE /resource/{id} -> actionDelete -> Delete the resource

GET/resource -> actionIndex -> 列出所有资源

GET /resource -> actionIndex -> List all the resources

URL 路由规则和动作定义可以在 \yii\rest\ActiveController\yii\rest\UrlRule 和相应的 \yii\ 中找到休息\*动作.

The URL routing rules and actions definition can be found in \yii\rest\ActiveController, \yii\rest\UrlRule and the respective \yii\rest\*Action.

其次,如果你想在控制器中添加额外的restful API,你可以简单地编写你额外的actionXxxxx(),并在配置中,在urlManager下添加以下url规则代码>:

Secondly, if you want to add extra restful API in the controller, you can simply write your extra actionXxxxx(), and in configuration, add the following url rules under urlManager:

'urlManager' => [
    'enablePrettyUrl' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class' => 'yii\rest\UrlRule',
            'controller' => ['resource'],
            'pluralize' => false,
            'extraPatterns' => [
                'POST {id}/your_preferred_url' => 'xxxxx', // 'xxxxx' refers to 'actionXxxxx'
            ],
        ],
    ],
],

实际上,这将生成一个新的路由规则,请求 POST/resource/{id}/your_preferred_url 将调用您的 ResourceController 的 actionXxxxx.

Effectively, this will generate a new routing rule, requesting POST /resource/{id}/your_preferred_url will invoke actionXxxxx of your ResourceController.

这篇关于Yii2 Restful API - 添加新操作的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆