【问题标题】:PhalconPHP - redirect in initialize()PhalconPHP - 在初始化()中重定向
【发布时间】:2016-05-31 16:59:10
【问题描述】:

在我的项目中,我创建了操作 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 获取内容。如何修复?

【问题讨论】:

  • 也许您可以为此使用中间件?

标签: php phalcon


【解决方案1】:

请尝试在beforeExecuteRoute() 中做同样的事情。 Phalcon 的initialize(),顾名思义,就是为了初始化事物而设计的。您可以使用调度程序在那里调度,但不应重定向。

您可以查看部分文档here。栏目“可以停止运行吗?”表示是否可以返回响应对象以完成请求或false 停止评估其他方法并编译视图。

有一点值得了解的是,beforeExecuteRoute() 在每次调用动作之前都会执行一次,因此可能会触发几次,以防您在动作之间进行转发。

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

【讨论】:

    【解决方案2】:

    我建议通过 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 方法以防有人需要。它演示了正确的标头处理(再次用于 SEO 目的)

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

    【讨论】:

    • 我收到警告 - forward 是无效函数。
    • 我的错。更新了我上面的答案。复制了您的代码并忘记删除返回。对不起:)
    • 好的,警告消失了,但我仍然从 IndexAction 获取内容。没有转发到 404 页面 :(
    • 您可以阅读这里的初始化控制器部分:docs.phalconphp.com/en/latest/reference/… 并确保您满足使用 initialize() 的要求吗?
    • 如果我在 forward() 之前 var_dump 某些东西,我会看到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多