如何解决通过action指定Yii2控制器中的动作请求动词
我知道有一种方法可以在Yii2的路由中指定这样的请求动词(在routes.php中):
[
'POST users' => 'user/create','GET users' => 'user/index',]
但是有没有一种方法可以在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是为此而制成的。
通常,您将此行为附加在控制器中,并且应该这样做,因为您要对添加的操作负责。
如果无法以某种方式将其添加到控制器中,则可以在操作类中实现 const Swiper = () => {
const [hasNext,setHasNext] = React.useState(true);
const [hasPrev,setHasPrev] = React.useState(true);
const [labelPrev] = React.useState("PREVIOUS");
const [labelNext] = React.useState("NEXT");
const clickHandler = () => {
console.log("clickHandlerCalled");
};
return (
<Carousel
renderArrowPrev={(clickHandler,hasPrev,labelPrev) => (
<img
style={{ height: "30px",width: "30px" }}
src={`assets/img/previous.svg`}
/>
)}
renderArrowNext={(clickHandler,hasNext,labelNext) => (
<img
style={{ height: "30px",width: "30px" }}
src={`assets/img/next.svg`}
/>
)}
onChange={onChange}
renderThumbs={() => null}
>
{getSlides()}
</Carousel>
);
};
,例如:
beforeRun()
这是直接从VerbFilter获取的。
由于这是动作的一部分,因此您可以准备一些将使用允许的动词的属性,以便可以在控制器的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;
}
方法中对其进行配置。但是正如我所说,将其简单地添加到控制器中要简单得多。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。