PhalconPHP - 重定向初始化()

问题描述:

在我的项目中,我创建了AjaxController,它运行了ajax请求。 我想用户输入到由ajax使用的URL获取404错误。 在AjaxController.php我:PhalconPHP - 重定向初始化()

public function initialize() { 
    if (!$this->request->isAjax()) { 
     return $this->response->redirect('error/show404'); 
    } 
} 

(当然,我有ErrorController与show404Action)

它不工作。当我在浏览器中输入example.com/ajax时,我从AjaxController的IndexAction中获取内容。如何修复它?

+0

也许你可以使用这个中间件? –

请尝试做相同的beforeExecuteRoute()。 Phalcon的initialize()正如其名称所述,旨在初始化事物。您可以使用调度程序进行调度,但不应该重定向。

您可以检查部分文档here。列“可以停止操作吗?”说如果可以返回响应对象来完成请求或者false停止评估其他方法并编译视图。

一个宝贵的知道的事情是,beforeExecuteRoute()每次在动作被调用之前执行,所以如果您在动作之间转发,可能会触发几次。

public function beforeExecuteRoute(Event $event, Dispatcher $dispatcher) 
{ 
    if (!$this->request->isAjax()) { 
     return $this->response->redirect('error/show404'); 
    } 
} 

我建议通过分派器转发用户到404页面。通过这种方式,网址将保持不变,您将根据搜索引擎优化规则做所有事情

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方法,以防有人需要它。它演示了正确的头处理(再次SEO的目的)

// 404 
public function error404Action() 
{ 
    $this->response->setStatusCode(404, 'Not Found'); 
    $this->view->pick(['templates/error-404']); 
    $this->response->send(); 
} 
+0

我得到警告 - 转发是无效的功能。 – Robin71

+0

我的不好。上面更新了我的答案。复制了您的代码并忘记取消退货。对不起:) –

+0

好吧,警告消失了,但我仍然从IndexAction获得内容。没有转发到404页面:( – Robin71