在 beforeAction 中渲染视图时在 Yii 中出现 "Headers already sent" 错误

Getting a "Headers already sent" error in Yii when rendering a view in beforeAction

我读过 Yii2 的处理程序,但我不知道如何在这种情况下正确使用它们。

基本上在我的 SiteController 中,我有:

class SiteController extends \app\components\Controller
{
    public function beforeAction($action)
    {
        // Makes some checks and if it's true, will render a file and stop execution of any action
        if (...)
            echo $this->render('standby');
            return false;
        }
        return true;
    }

    // All my other actions here
}

这似乎运行良好并停止了执行,但是我得到了 render() 行的 "Headers already sent",就好像它在进行重定向一样。

如果我写 Yii::$app-end() 而不是 return false,同样的事情也会发生。

如果我写 exit(); 而不是 return false,则不会显示异常,但不会显示调试面板,因为 Yii 没有正确终止。

我尝试删除 echo $this->render(..) 结果是一个空页面,没有任何重定向,这似乎只是 Yii 抱怨我从控制器回显内容。

当然我不能 return render() 或 return true 的结果,因为它会执行我正在尝试的页面操作避免并在这里结束。

我知道 returning false in beforeAction() 触发器 EVENT_BEFORE_ACTION 但我不知道我应该在哪里使用它。 events documentation 并没有真正帮助我。

那么有没有办法显示 "standby" 视图,防止执行其他操作并避免从 Controller 回显的错误消息?

请注意,我正在努力完成这项工作,而不必在每个操作方法中重复代码来检查 beforeAction() 的结果是否为假。

从 Yii 2.0.14 开始,您不能在控制器中回显 - 响应必须由操作返回。如果你想在 beforeAction() 中生成响应,你需要设置 Yii::$app->response 组件而不是回显内容:

public function beforeAction($action) {
    // Makes some checks and if it's true, will render a file and stop execution of any action
    if (...) {
        Yii::$app->response->content = $this->render('standby');
        Yii::$app->response->statusCode = 403; // use real HTTP status code here

        return false;
    }

    return parent::beforeAction($action);
}

不要忘记调用 parent::beforeAction($action) - 省略它会导致意外且难以调试的行为。