在Yii2 Rest API中创建自定义操作

时间:2021-06-06 19:33:32

I am working with yii2 , and I want to create rest api. I read yii2 rest api quick start documentation, but in there you can use only default actions(index/view/create/delete/list...). It is working fine

我正在使用yii2,我想创建rest api。我阅读了yii2 rest api快速入门文档,但在那里你只能使用默认动作(index / view / create / delete / list ...)。它工作正常

But I want to create another action for example

但我想创建另一个例子

public function actionPurchasedcard(){
     //some code
}

But I couldn't it. Help me please, how to create custome action in yii2 Rest api.

但我不能。请帮助我,如何在yii2 Rest api中创建客户行动。

config.php

config.php文件

'urlManager' => [
    'enablePrettyUrl' => true,
    'enableStrictParsing' => true,
    'showScriptName' => false,
    'rules' => [
        [
            'class'=>'yii\rest\UrlRule',
            'controller'=>[
                'v1/resource',
            ]
        ],
    ]
]

document root:

文件根:

htdocs/myapi/api/web/

I am calling like this : http://myapi/v1/resource/purchasedcard

我这样打电话:http:// myapi / v1 / resource / purchasecard

Thanks.(sorry my english not good)

谢谢。(抱歉我的英语不好)

1 个解决方案

#1


20  

You may set the extraPatterns key in a rule to add a new actions, like so:

您可以在规则中设置extraPatterns键以添加新操作,如下所示:

'rules' => [
    [
        'class'=>'yii\rest\UrlRule',
        'controller'=>[
            'v1/resource',
        ],
        'extraPatterns' => [
            'GET purchasedcard' => 'purchasedcard',
        ]
    ],
]

You may want to add other properties to the rule such as prefix or only depending on what you want to achieve. Look at the full documentation to know more. Look at guide examples too: there is an example of an extraPattern with the search action near the end of this guide.

您可能希望将其他属性添加到规则中,例如前缀或仅取决于您要实现的目标。查看完整的文档以了解更多信息。另请参阅指南示例:在本指南末尾附近有一个带有搜索操作的extraPattern示例。

#1


20  

You may set the extraPatterns key in a rule to add a new actions, like so:

您可以在规则中设置extraPatterns键以添加新操作,如下所示:

'rules' => [
    [
        'class'=>'yii\rest\UrlRule',
        'controller'=>[
            'v1/resource',
        ],
        'extraPatterns' => [
            'GET purchasedcard' => 'purchasedcard',
        ]
    ],
]

You may want to add other properties to the rule such as prefix or only depending on what you want to achieve. Look at the full documentation to know more. Look at guide examples too: there is an example of an extraPattern with the search action near the end of this guide.

您可能希望将其他属性添加到规则中,例如前缀或仅取决于您要实现的目标。查看完整的文档以了解更多信息。另请参阅指南示例:在本指南末尾附近有一个带有搜索操作的extraPattern示例。