Zend _forward() 在 preDispatch() 中不起作用


Zend _forward() does not work in preDispatch()?

我目前正在从我的Zend MVC应用程序构建一个控制器,该控制器仅用作json服务来填充页面。我想限制用户仅使用 GET 方法来访问此端点(出于某些安全原因)。

我在Zend中关注了这篇文章_forward()不起作用? 但无法开始工作。

我正在使用 preDispatch 来检测非获取请求,并希望转发到同一控制器中的错误操作。我的代码看起来像这样,

public function preDispatch(){
    $this->_helper->layout()->disableLayout();
    $this->_helper->viewRenderer->setNoRender();
    //Restrict this Controller access to Http GET method
    if(!($this->getRequest()->isGet())){
        return $this->_forward('error');
    }
}
public function errorAction(){
    $this->getResponse()->setHttpResponseCode(501);
    echo "Requested Method is not Implemented";
}

当我使用发布请求测试页面时,它会抛出

PHP 致命错误:超出 30 秒的最大执行时间

我让它一起工作

$this->_redirect("service/error");

想知道这是否是处理这种情况的唯一/最佳方法。

任何帮助将不胜感激。提前谢谢。

调用

_forward不起作用的原因是因为请求方法不会更改,因此您最终会陷入无限循环,尝试转发到error操作,因为请求始终POST

_forward通过修改调度请求时将调用的模块、控制器和操作来工作,_redirect实际上返回 302 重定向并导致浏览器发出额外的 HTTP 请求。

这两种方法都可以,但我更愿意使用_forward因为它不需要额外的 HTTP 请求(但您仍然保证POST请求被拒绝)。

此代码应该适合您:

    if(!($this->getRequest()->isGet())){
        // change the request method - this only changes internally
        $_SERVER['REQUEST_METHOD'] = 'GET';
        // forward the request to the error action - preDispatch is called again
        $this->_forward('error');
        // This is an alternate to using _forward, but is virtually the same
        // You still need to override $_SERVER['REQUEST_METHOD'] to do this
        $this->getRequest()
             ->setActionName('error')
             ->setDispatched(false);
    }