本文介绍了Yii2宁静的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.

首先,该框架包括 \\警予\\其他\\ ActiveController ,提供典型的宁静API操作和URL管理。

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

基本上,控制器predefines CRUD操作如下:

Basically, the controller predefines the CRUD operations as followed:

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

POST /resource -> actionCreate -> Create the resource

GET /资源/ {ID} - > 的actionView - >读取资源

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

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

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

删除/资源/ {ID} - > actionDelete - >删除资源

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

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

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

该URL路由规则和定义可在 \\警予\\其余找到行动\\ ActiveController \\警予\\其他\\ UrlRule 和相应的 \\警予\\其他\\ *操作

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(),并在配置,下添加下列URL规则 urlManager

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 /资源/ {ID} / your_ preferred_url 将调用 actionXxxxx 您ResourceController的。

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

这篇关于Yii2宁静的API - 例如,要添加一个新的动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 23:11