Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
733 views
in Technique[技术] by (71.8m points)

rest - Yii2 Restful API - Example to Add a New Action

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

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

Basically, the controller predefines the CRUD operations as followed:

POST /resource -> actionCreate -> Create the resource

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

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

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

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

The URL routing rules and actions definition can be found in yii estActiveController, yii estUrlRule and the respective yii est*Action.

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
estUrlRule',
            'controller' => ['resource'],
            'pluralize' => false,
            'extraPatterns' => [
                'POST {id}/your_preferred_url' => 'xxxxx', // 'xxxxx' refers to 'actionXxxxx'
            ],
        ],
    ],
],

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...