简体   繁体   English

通过 actions() 在 Yii2 控制器中指定动作的请求动词

[英]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):我知道有一种方法可以在 Yii2 的路由中指定请求动词,如下所示(在 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?但是有没有办法在actions()方法中的控制器内部执行此actions() 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其中 yii 解释为有效路由, /user/create 显示 404 和

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

which said that 'verb' is an unknown property of ActionCreate其中说“动词”是 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另一个解决方案是对 GET 和 POST 使用相同的操作,并在请求方法上做不同的事情,但我想把事情分开

Yes, you can do it andVerbFilter is made for that.是的,您可以做到,而VerbFilter就是为此而生的。

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:如果以某种方式将它添加到控制器中是不可能的,您可以在操作类中实现beforeRun() ,例如:

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.顺便说一下,这直接取自 VerbFilter。

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.并且由于这将是操作的一部分,您可以准备一些将采用允许的动词的属性,以便您能够在控制器的actions()方法中配置它。 But as I said, simply adding it in the controller is much simpler.但正如我所说,简单地将它添加到控制器中要简单得多。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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