[英]specify request verb for action in Yii2 controller through actions()
我知道有一种方法可以在 Yii2 的路由中指定请求动词,如下所示(在 routes.php 中):
[
'POST users' => 'user/create',
'GET users' => 'user/index',
]
但是有没有办法在actions()
方法中的控制器内部执行此actions()
? 喜欢:
class ExampleController extends Controller {
public function actions() {
return [
'create' => [
'class' => ActionCreate::class,
'verb' => 'POST'
],
'index' => [
'class' => ActionIndex::class,
'verb' => 'GET'
]
];
}
}
我试过:
'GET create' => ActionCreate::class
其中 yii 解释为有效路由, /user/create 显示 404 和
'create' => [
'class' => ActionCreate::class,
'verb' => 'GET'
]
其中说“动词”是 ActionCreate 的未知属性
我问这个的原因是因为我想让我的应用程序使用尽可能少的显式路由
另一个解决方案是对 GET 和 POST 使用相同的操作,并在请求方法上做不同的事情,但我想把事情分开
是的,您可以做到,而VerbFilter就是为此而生的。
通常你会在控制器中附加这个行为,你应该这样做,因为你对添加的动作负责。
如果以某种方式将它添加到控制器中是不可能的,您可以在操作类中实现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;
}
顺便说一下,这直接取自 VerbFilter。
并且由于这将是操作的一部分,您可以准备一些将采用允许的动词的属性,以便您能够在控制器的actions()
方法中配置它。 但正如我所说,简单地将它添加到控制器中要简单得多。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.