简体   繁体   中英

specify request verb for action in Yii2 controller through actions()

I know there is a way to specify the request verb in Yii2's routes like this (in routes.php):

[
    'POST users' => 'user/create',
    'GET  users' => 'user/index',
]

but is there a way to do that inside of a controller in the actions() method? like:

class ExampleController extends Controller {
    public function actions() {
        return [
            'create' => [
                'class' => ActionCreate::class,
                'verb' => 'POST'
            ],
            'index' => [
                'class' => ActionIndex::class,
                'verb' => 'GET'
            ]
        ];
    }
}

I tried:

'GET create' => ActionCreate::class

which yii interpreted as a valid route and /user/create showed a 404 and

'create' => [
    'class' => ActionCreate::class,
    'verb' => 'GET'
]

which said that 'verb' is an unknown property of ActionCreate
The reason I'm asking this is because I want to make my app use as little explicit routing as possible
The other solution for this is to use the same action for both GET and POST and do things differently on the request method but I would like to keep things separated

Yes, you can do it andVerbFilter is made for that.

Usually you are attaching this behavior in the controller and you should do it like that since you are responsible for the actions added.

If somehow adding it in the controller is not possible, you can implement beforeRun() in the action class like:

public function beforeRun()
{
    $verb = \Yii::$app->getRequest()->getMethod();
    $allowed = [/*list of allowed uppercased verbs here*/];
    if (!in_array($verb, $allowed)) {
        \Yii::$app->getResponse()->getHeaders()->set('Allow', implode(', ', $allowed));
        throw new \yii\web\MethodNotAllowedHttpException('Method Not Allowed. This URL can only handle the following request methods: ' . implode(', ', $allowed) . '.');
    }

    return true;
}

This is taken straight from the VerbFilter by the way.

And since this is will be a part of action you can prepare some property that will take the allowed verbs so you will be able to config it in controller's actions() method. But as I said, simply adding it in the controller is much simpler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM