Cakephp-Calling Parent render() function from Appcontroller gives Error: Call to a member function send() on a non-object

Cakephp-Calling Parent render() function from Appcontroller gives Error: Call to a member function send() on a non-object

我正在尝试使用 cakephp 构建一个应用程序;这将生成多种格式的输出(xml、json、自定义、html)。

根据某些属性,将决定输出格式。 我想要的是,如果 html 是输出类型;然后我希望应用程序像往常一样渲染视图(常规控制器->渲染);否则数据应以其他格式呈现

这就是我想要做的。 我在 AppController.php 中重写了函数渲染,如下所示 -

public function render($view = null, $layout = null) {
    if ($this->rType == "json") {
        $this->_renderJson();
    } else if ($this->rType == "xml") {
        $this->_renderXml();
    } else if ($this->rType == "custom") {
        $this->_renderCustom();
    } else {
        parent::render($view,$layout);
    }
}

这与其他格式完美兼容,但 html。

我希望呼叫应该像正常的 cakephp 流程一样转接至 Controller::render。相反,它给了我以下错误

错误:调用非对象文件上的成员函数 send():/xx/lib/Cake/Routing/Dispatcher。php 行:174

任何想法 - 我该如何解决这个问题?

覆盖内容时,您必须确保覆盖的方法与原始实现相匹配,包括它采用的参数和它 returns 的值。

您的 render() 方法缺少正确的 return 值,该值应该是 CakeResponse 的实例,稍后将由调度程序使用。

https://github.com/cakephp/cakephp/blob/2.6.0/lib/Cake/Controller/Controller.php#L930

https://github.com/cakephp/cakephp/blob/2.6.0/lib/Cake/Routing/Dispatcher.php#L174

因此,将您的自定义渲染方法更改为 return $this->response,并在覆盖的 render() 方法中添加适当的 return:

public function render($view = null, $layout = null) {
    if ($this->rType == "json") {
        return $this->_renderJson();
    } else if ($this->rType == "xml") {
        return $this->_renderXml();
    } else if ($this->rType == "custom") {
        return $this->_renderCustom();
    } else {
        return parent::render($view,$layout);
    }
}

将 return 添加到 Controller::render() 语句确实如 ndm 所说的那样成功了。 此外,我发现的另一种解决方法是使用 beforeRender()。

public function beforeRender(){
    parent::beforeRender();
    if ($this->rType == "json") {
        $this->_renderJson();
        return false;
    } else if ($this->rType == "xml") {
        $this->_renderXml();
        return false;
    } else if ($this->rType == "custom") {
        $this->_renderCustom();
        return false;
    }
    return true;

}

这也有效....

谢谢。