PhalconPHP - 在 initialize() 中重定向
PhalconPHP - redirect in initialize()
在我的项目中,我创建了操作 ajax 请求的 AjaxController。
我想输入 ajax 使用的 url 的用户得到 404 错误。
在 AjaxController.php 我有:
public function initialize() {
if (!$this->request->isAjax()) {
return $this->response->redirect('error/show404');
}
}
(当然我有带 show404Action 的 ErrorController)
没用。当我在浏览器中输入 example.com/ajax 时,我从 AjaxController 中的 IndexAction 获取内容。如何修复?
我建议通过 Dispatcher 将用户转发到 404 页面。这样 URL 将保留,您将根据 SEO 规则执行所有操作。
public function initialize() {
if (!$this->request->isAjax()) {
$this->dispatcher->forward(['controller' => 'error', 'action' => 'show404']);
}
}
此外,在初始化时进行重定向也不是一个好主意。来自 Phalcon 的更多信息:https://forum.phalconphp.com/discussion/3216/redirect-initialize-beforeexecuteroute-redirect-to-initalize-and
添加我的 404 方法以备不时之需。它演示了正确的 header 处理(再次用于 SEO 目的)
// 404
public function error404Action()
{
$this->response->setStatusCode(404, 'Not Found');
$this->view->pick(['templates/error-404']);
$this->response->send();
}
请尝试在 beforeExecuteRoute()
中做同样的事情。 Phalcon 的 initialize()
顾名思义,就是用来初始化东西的。您可以使用调度程序在那里调度,但不应重定向。
您可以查看部分文档 here。列 "can stop operation?" 表示是否可以 return 响应对象完成请求或 false
停止评估其他方法并编译视图。
值得一提的是,beforeExecuteRoute()
每次都在调用操作之前执行,因此如果您在操作之间转发,可能会触发几次。
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
if (!$this->request->isAjax()) {
return $this->response->redirect('error/show404');
}
}
在我的项目中,我创建了操作 ajax 请求的 AjaxController。 我想输入 ajax 使用的 url 的用户得到 404 错误。 在 AjaxController.php 我有:
public function initialize() {
if (!$this->request->isAjax()) {
return $this->response->redirect('error/show404');
}
}
(当然我有带 show404Action 的 ErrorController)
没用。当我在浏览器中输入 example.com/ajax 时,我从 AjaxController 中的 IndexAction 获取内容。如何修复?
我建议通过 Dispatcher 将用户转发到 404 页面。这样 URL 将保留,您将根据 SEO 规则执行所有操作。
public function initialize() {
if (!$this->request->isAjax()) {
$this->dispatcher->forward(['controller' => 'error', 'action' => 'show404']);
}
}
此外,在初始化时进行重定向也不是一个好主意。来自 Phalcon 的更多信息:https://forum.phalconphp.com/discussion/3216/redirect-initialize-beforeexecuteroute-redirect-to-initalize-and
添加我的 404 方法以备不时之需。它演示了正确的 header 处理(再次用于 SEO 目的)
// 404
public function error404Action()
{
$this->response->setStatusCode(404, 'Not Found');
$this->view->pick(['templates/error-404']);
$this->response->send();
}
请尝试在 beforeExecuteRoute()
中做同样的事情。 Phalcon 的 initialize()
顾名思义,就是用来初始化东西的。您可以使用调度程序在那里调度,但不应重定向。
您可以查看部分文档 here。列 "can stop operation?" 表示是否可以 return 响应对象完成请求或 false
停止评估其他方法并编译视图。
值得一提的是,beforeExecuteRoute()
每次都在调用操作之前执行,因此如果您在操作之间转发,可能会触发几次。
public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher)
{
if (!$this->request->isAjax()) {
return $this->response->redirect('error/show404');
}
}