[英]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.