我已经阅读了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
}
Run Code Online (Sandbox Code Playgroud)
这似乎运行良好,并停止执行,但我得到该行的"已发送标题" render(),就好像它正在进行重定向.
如果我写Yii::$app-end()而不是return false,同样的事情发生.
如果我写exit();而不是return false,没有异常显示,但调试面板没有显示,因为Yii没有正确终止.
我尝试删除echo $this->render(..),它导致一个空页面,没有任何重定向,这似乎只是Yii抱怨我从Controller回应的东西.
当然,我无法返回结果render()或返回true,因为它将执行页面的操作,我试图避免并在此结束.
我知道在beforeAction()触发器中返回false EVENT_BEFORE_ACTION但我没有看到我应该使用它的位置.该事件的文件并没有真正帮助我.
那么有没有办法显示"待机"视图,阻止执行其他操作,并避免错误消息从Controller?
请注意,我正在努力完成这项工作,而不必在每个操作方法中复制代码以检查结果是否beforeAction()为false.
rob*_*006 10
由于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);
}
Run Code Online (Sandbox Code Playgroud)
不要忘记调用parent::beforeAction($action)- 省略它会导致意外和难以调试的行为.
| 归档时间: |
|
| 查看次数: |
1982 次 |
| 最近记录: |