我在控制器中有一个动作,我调用一个函数来检查是否设置了cookie,如果cookie没有设置,那么它应该重定向到其他地方。
在同一个控制器中,我有一些变量的评估,如果他们没有设置,然后抛出一个禁止异常但即使cookie没有设置,它也不会重定向,禁止消息出现
正确的操作应该是重定向,而不是在cookie不存在时对变量进行评估,或者至少这是我需要的。
这个函数在appController
中public function isCookieSet(){
if(!$this->Cookie->check('cookie')){
return $this->redirect($this->referer());
}
}
控制器中的代码
public function editarImg($negocio_id=null){
$this->isCookieSet(); //should redirect here
//but executes until here
if((!isset($this->perRol['crear_negocios']) || $this->perRol['crear_negocios']==0) ||
(!isset($this->perRol['cargar_elim_imagenes']) || $this->perRol['cargar_elim_imagenes']==0)){
throw new ForbiddenException($this->getMensajeError(403));
}
...
}
问题中的代码可以这样重写(为了更清晰):
public function editarImg($negocio_id=null){
if(!$this->Cookie->check('cookie')){
$this->redirect($this->referer());
}
// more code
调用redirect
的返回值被忽略,"更多代码"是否总是被执行?
这不是redirect
方法的预期调用方式,正如文档中提到的(强调添加):
该方法将返回具有适当标头集的响应实例。你应该从你的动作返回响应实例,以防止视图渲染,并让调度程序处理实际的重定向。
迁移指南中也提到了这一点:
代码范例
CakeControllerController::redirect()
的签名已更改为Controller::redirect(string|array $url, int $status = null)
。第三个参数$exit被删除了。该方法不能再发送响应和退出脚本,而是返回一个具有适当头集的response实例。
问题中的代码需要与以下代码等价:
public function editarImg($negocio_id=null){
if(!$this->Cookie->check('cookie')){
return $this->redirect($this->referer()); # <- return the response object
}
// more code
试试这个,它应该可以工作:
public function isCookieSet(){
if(!$this->Cookie->check('cookie')){
// return $this->redirect($this->referer()); <- not working
$this->response = $this->redirect($this->referer());
$this->response->send();
exit;
}
}